2017-10-04 24 views
2

這可能聽起來很愚蠢,但我找不到指導。我們可以通過自定義函數訪問傳遞給組件的道具嗎?

我想要做的是更改父項中名爲update的變量。

,並在父DOM做:

<Child update={this.state.update} /> 

和孩子,而不是拿起它渲染和回報(與const {update} = this.props)之間,只能夠在DOM使用它,我想在構造函數和渲染之間的部分選取它並在那裏使用它。

回答

2

您可以訪問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); 
    } 
} 
+0

我嘗試從'NewProps.update'或'props.update''Uncaught(in promise)console.log中嘗試在'componentWillReceiveProps(NewProps)'中使用它TypeError:無法讀取屬性'update'未定義的' – tatsu

+0

'Child.'構造函數中的'this.state'是什麼? –

+0

不要我必須確保從聲明中排除另一個函數,這就是爲什麼 – tatsu

1

陣營有稱爲組件功能的生命週期:componentWillReceiveProps()

否則:https://reactjs.org/docs/react-component.html

在組件啓動時如果希望基於道具來改變狀態改變使用您可以使用componentDidMount()

如果你想讓這個函數的結果在你的視圖中用作數據(但只是被操縱)。比起製作一個單獨的函數,也稱爲:計算函數的計算屬性。 (因爲結果是根據當前狀態/道具計算的)。 React將確保您不會重新渲染/計算不必要。

+0

我想在'使用它componentWillReceiveProps(NewProps)''當我嘗試從'NewProps.update'或'props.update''uncaught(在promise中)console.log時TypeError:無法讀取未定義的屬性'update' – tatsu

+0

@tatsu這很奇怪,我不知道你的代碼是怎樣的。這是不正常的。你也應該使用'this.props.update' ofcourse –

+0

我想到它是因爲我試圖從newProps實例化一個函數,儘管它不是來自那裏。 – tatsu

相關問題