如果你想通過國家{名的 「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} />
);
}
}
[提升狀態上]( https://facebook.github.io/react/docs/lifting-state-up.html)和[Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html)會告訴你做這些事情的更習慣的方式。 –