在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ React ant.design Modal對(duì)話框怎么觸發(fā)子組件的動(dòng)作?

React ant.design Modal對(duì)話框怎么觸發(fā)子組件的動(dòng)作?

如何通過(guò)React中的父組件,觸發(fā)子組件中的動(dòng)作。


import {Modal} from 'antd'

<Modal
  visible={this.state.componentModalVisible}
  title="父組件"
  onOk={this.handleOk}
  onCancel={this.handleCancel}
  footer={[
    <Button key="back" onClick={this.handleCancel}>取消</Button>,
    <Button key="submit" type="primary" onClick={this.handleOk}>保存</Button>
  ]}>
  <Child /> // 希望父組件的`保存`按鈕觸發(fā)子組件中的動(dòng)作,或者獲取子組件中的state信息也可以
</Modal>
回答
編輯回答
喵小咪

既然保存按鈕在父組件,為什么不將要保存的所有信息以及用到的方法也存在父組件中呢?然后將父組件中的this 傳給子組件,子組件可以通過(guò)props 來(lái)得到數(shù)據(jù)或者改變數(shù)據(jù)。

<Child parent={this}/> // 這里將父組件的this傳給子組件;

//子組件通過(guò)
this.props.parent.state.父組件數(shù)據(jù); //拿到父組件的數(shù)據(jù)
this.props.parent.setState({父組件數(shù)據(jù):新數(shù)據(jù)});//改變父組件的數(shù)據(jù)
this.props.parent.父組件方法;//調(diào)用父組件的方法

2017年5月12日 19:56
編輯回答
尐懶貓

父組件可以用ref掉起自組件的方法。
for example:

//父組件
<Modal
  visible={this.state.componentModalVisible}
  title="父組件"
  onOk={this.ref.child.handleClick}
  onCancel={this.handleCancel}
  footer={[
    <Button key="back" onClick={this.handleCancel}>取消</Button>,
    <Button key="submit" type="primary" onClick={this.handleOk}>保存</Button>
  ]}>
  <Child ref={(c)=>{this.child=c}} /> // 希望父組件的`保存`按鈕觸發(fā)子組件中的動(dòng)作,或者獲取子組件中的state信息也可以
</Modal>

//子組件
handleClick(){
    //...
}
2018年5月13日 19:25
編輯回答
久舊酒

父組件要想獲取子組件的state,只能通過(guò)回調(diào)函數(shù),例如:

getData = (data)=>{
    console.log('子組件data',data)
}

<child getData={this.getData} />

// child

onClick={()=>{
    const data = this.state.data;
    this.props.getData(data);
}}
2017年11月26日 10:02