呼啦一陣風
2024-01-18 20:48:32
我有一個父組件,其狀態帶有主題字符串。(目前僅用于測試目的,因此請不要對它的實用性考慮太多:)?。┗旧?,這是迄今為止的布局。父組件攜帶主題的狀態。父組件使用代碼“theme={this.state.theme}”將當前狀態作為“theme”屬性傳遞給子組件。嘗試將子元素樣式設置為內聯style={{ background: this.props.theme === "light" ? "#fff" : "#000" }}得到錯誤:TypeError: Cannot read property 'props' of undefined。我知道這是因為“這個”是如何綁定的。然而,最好的方法是什么?我希望子元素與父組件的狀態匹配,但我需要正確綁定“this”。
2 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
看來您正在為未分配的子元素使用功能組件this,請嘗試更改為
//remove the `this`
style={{ background: props.theme === "light" ? "#fff" : "#000" }}

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
我知道這個問題已經得到解答,但這里有一個提示。當你有一個函數組件時,你可以像這樣訪問 prop:
someRandomFunc = ({props}) => {
return(
<Text
style={{ background: props.theme === "light" ? "#fff" : "#000" }}>HELLO WORLD</Text>
}
);
如果它是一個類組件。您可以直接使用this.props:
class Something extends React.Component{
state = {}
render(){
return(
<Text style={{ background: this.props.theme === "light" ? "#fff" : "#000" }}></Text>
)
}
}
希望這對將來有幫助!
添加回答
舉報
0/150
提交
取消