亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從父級調用子方法

從父級調用子方法

動漫人物 2019-07-06 13:19:55
從父級調用子方法我有兩個組成部分。父組件子組件我試圖從父母那里調用孩子的方法,我試過這樣做,但沒有得到結果class Parent extends Component {   render() {     return (       <Child>         <button onClick={Child.getAlert()}>Click</button>       </Child>       );     }   }class Child extends Component {   getAlert() {     alert('clicked');   }   render() {     return (       <h1 ref="hello">Hello</h1>     );   }}有辦法從父級調用子方法嗎?注意:子組件和父組件位于兩個不同的文件中。
查看完整描述

3 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

您可以在這里使用另一個模式:

class Parent extends Component {
 render() {
  return (
    <div>
      <Child setClick={click => this.clickChild = click}/>
      <button onClick={() => this.clickChild()}>Click</button>
    </div>
  );
 }}class Child extends Component {
 constructor(props) {
    super(props);
    this.getAlert = this.getAlert.bind(this);
 }
 componentDidMount() {
    this.props.setClick(this.getAlert);
 }
 getAlert() {
    alert('clicked');
 }
 render() {
  return (
    <h1 ref="hello">Hello</h1>
  );
 }}

它所做的就是設置父母的clickChild方法在安裝子節點時使用。這樣,當您單擊父節點中的按鈕時,它將調用clickChild這叫孩子的getAlert.

如果您的孩子是用connect()所以你不需要getWrappedInstance()黑客。

注意你不能用onClick={this.clickChild}在父級中,因為當父級呈現時,子級沒有被掛載。this.clickChild還沒有分配。使用onClick={() => this.clickChild()}很好,因為當您單擊按鈕時this.clickChild應該已經被分配了。


查看完整回答
反對 回復 2019-07-06
  • 3 回答
  • 0 關注
  • 1214 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號