Nếu bạn muốn vượt qua tình trạng {name: "helloworld"} làm điều đó như thế:
class App extends React.Component {
constuctor(props) {
super(props);
this.state = {name:"helloworld"};
}
render() {
return(
<ChildComponent {...this.state} />
);
}
}
và trong thành phần con bạn có thể làm:
<Text>{this.props.name}</Text>
Nhưng nếu bạn muốn vượt qua các đạo cụ của các thành phần để nó trẻ:
class App extends React.Component {
constuctor(props) {
super(props);
this.state = {name:"helloworld"};
}
render() {
return(
<ChildComponent {...this.props} />
);
}
}
và trong thành phần con bạn có thể làm:
<Text>{this.props.stuff}</Text>//place stuff by any property name in props
Bây giờ, nếu bạn muốn cập nhật trạng thái của thành phần gốc từ thành phần con, bạn sẽ cần chuyển hàm cho thành phần con:
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)} />
);
}
}
và sau đó trong thành phần con bạn có thể sử dụng này: this.props.update('new name')
CẬP NHẬT
sử dụng constructor es6 hơn và loại bỏ
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} />
);
}
}
[Nâng Nhà nước Up] (https://facebook.github.io/react/docs/lifting-state-up.html) và [Suy nghĩ trong React] (https://facebook.github.io/react/docs/thinking-in-react.html) sẽ cho bạn thấy cách làm việc thành ngữ hơn. –