標題名很長,其實說白了就是——子組件傳值給父組件,但我一開始覺得這兩種情況是不一樣的。
查了一下資料,這種情況有一個專用語“狀態提升”。這是官方文檔:https://doc.react-china.org/react/docs/lifting-state-up.html
基本思想就是在父組件中定義一個state(這里是value)和改變這個state的函數(這里是setValue),然后把這個函數(setValue)通過props傳給子組件;
子組件直接通過props中傳過來的函數來改變父組件中的value,最后父組件就可以直接用這個value。
class Child extends React.Component{
constructor() {
super();
this.state= {};
}
render(){
? return(
? ?<div onClick={()=>{this.props.setValue('aaa')}}></div>
? )
class Parent extends React.Component{
? ? ?constructor() {
? ? ? ? ? ? super();
? ? ? ? ? ? this.state= {value:''};
? ? ? ? ? ? this.setValue=this.setValue.bind(this);
? ? ?}
setValue(value) {
this.setState({
value
});
}
dosomething(){
console.log(this.state.value)
}
render(){
return(
<div>
<button onClick={()=>{this.dosomething()}}
?<Child setValue={this.setValue}
</div>
)
}