2017-01-16 84 views
5

我是React ES6中的新人,我想我正在以錯誤的方式修改狀態。我的代碼是這樣的,當我設置狀態的父組件:如何將父狀態傳遞給其子組件?

class App extends React.Component { 
constuctor(props) { 
    super(props); 
    this.state = {name:"helloworld"}; 
} 
render() { 
    return( 
    <ChildComponent parentObj={this} /> // parentObj for parent context as props on child components 
); 
} 
} 

我的問題是在其他的子組件,我必須repeatitively做到這一點,有沒有這樣做的另一種方式?我沒有React.createClass的問題,但我想在es6中編碼,所以我有這個問題。

如果你要發送的整個狀態
+1

[提升狀態上]( https://facebook.github.io/react/docs/lifting-state-up.html)和[Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html)會告訴你做這些事情的更習慣的方式。 –

回答

6

如果你想通過國家{名的 「HelloWorld」}那樣做:

class App extends React.Component { 
constuctor(props) { 
    super(props); 
    this.state = {name:"helloworld"}; 
} 
render() { 
    return( 
    <ChildComponent {...this.state} /> 
); 
} 
} 

和子組件,你可以這樣做:

<Text>{this.props.name}</Text> 

,但如果你想通過組件的道具給它的孩子:

class App extends React.Component { 
    constuctor(props) { 
     super(props); 
     this.state = {name:"helloworld"}; 
    } 
    render() { 
     return( 
     <ChildComponent {...this.props} /> 
    ); 
    } 
    } 

和子組件,你可以這樣做:

<Text>{this.props.stuff}</Text>//place stuff by any property name in props 

現在,如果要從子組件更新父組件的狀態,則需要將子組件的功能傳遞給子組件:

class App extends React.Component { 
    constuctor(props) { 
     super(props); 
     this.state = {name:"helloworld"}; 
    } 
    update(name){ 
     this.setState({name:name})// or with es6 this.setState({name}) 
    } 
    render() { 
    return( 
     <ChildComponent {...this.props, update: this.update.bind(this)} /> 
    ); 
    } 
    } 

,然後在子組件,您可以使用此:this.props.update('new name')

UPDATE

使用更ES6和去除構造

class App extends React.Component { 
    state = {name:"helloworld"}; 

    // es6 function, will be bind with adding .bind(this) 
    update = name => { 
     this.setState({name:name})// or with es6 this.setState({name}) 
    } 

    render() { 
    // notice that we removed .bind(this) from the update 
    return( 
     <ChildComponent {...this.props, update: this.update} /> 
    ); 
    } 
    } 
+0

我明白這一點,但我可以從子組件進行狀態更改嗎? –

+0

不是直接的,你可以傳遞一個函數,讓我們說它更新,我會編輯答案給你看! – challenger

+0

很清楚嗎?或者已經太晚了! :p – challenger

0

return(<ChildComponent {...this.state} />); 

但是,這可能是一個壞主意:)

編輯:在您的情況,這發出了一個「名稱」屬性,子組件與值 '的HelloWorld'

+0

是的,我明白,它發送'名稱'屬性,但我必須這樣做,所以我可以使用this.setState子組件,它的工作原理,但不知何故,我認爲這是'錯誤的方式 –

+0

爲什麼這是一個壞主意? –

+0

如果您從父母狀態重複發送到兒童,那麼您的組件模型可能不是那麼好:) –

相關問題