這可能聽起來很愚蠢,但我找不到指導。我們可以通過自定義函數訪問傳遞給組件的道具嗎?
我想要做的是更改父項中名爲update
的變量。
,並在父DOM做:
<Child update={this.state.update} />
和孩子,而不是拿起它渲染和回報(與const {update} = this.props
)之間,只能夠在DOM使用它,我想在構造函數和渲染之間的部分選取它並在那裏使用它。
這可能聽起來很愚蠢,但我找不到指導。我們可以通過自定義函數訪問傳遞給組件的道具嗎?
我想要做的是更改父項中名爲update
的變量。
,並在父DOM做:
<Child update={this.state.update} />
和孩子,而不是拿起它渲染和回報(與const {update} = this.props
)之間,只能夠在DOM使用它,我想在構造函數和渲染之間的部分選取它並在那裏使用它。
您可以訪問props
到組件的組件的任何地方,無論是在constructor, lifecycle functions, render or custom functions.
,你需要知道的唯一的事情就是constructor, lifecycle methods and render function
已經有binding
的陣營組成的範圍內,但對於custom function
你需要自己添加綁定。可以在constructor
中進行綁定,也可以將函數聲明爲arrow functions
。
檢查爲什麼你需要綁定自定義功能,這樣的回答:Why do we need to bind function and eventHandlers in React and what is the difference between the different binding methods
對於你的情況
<Child update={this.state.update} />
那裏的孩子可能是
class Child extends React.Component {
componentDidMount() {
const {update} = this.update || {};
console.log(update);
this.somefunc();
}
somefunc =() = {
const {update} = this.update || {}; //After function is binded, you can do the same thing here too
console.log(update);
}
}
陣營有稱爲組件功能的生命週期:componentWillReceiveProps()
否則:https://reactjs.org/docs/react-component.html
在組件啓動時如果希望基於道具來改變狀態改變使用您可以使用componentDidMount()
如果你想讓這個函數的結果在你的視圖中用作數據(但只是被操縱)。比起製作一個單獨的函數,也稱爲:計算函數的計算屬性。 (因爲結果是根據當前狀態/道具計算的)。 React將確保您不會重新渲染/計算不必要。
我嘗試從'NewProps.update'或'props.update''Uncaught(in promise)console.log中嘗試在'componentWillReceiveProps(NewProps)'中使用它TypeError:無法讀取屬性'update'未定義的' – tatsu
'Child.'構造函數中的'this.state'是什麼? –
不要我必須確保從聲明中排除另一個函數,這就是爲什麼 – tatsu