2017-08-16 46 views
1

ReactJS我試圖調用子組件中的函數,但是從另一個子組件中調用函數。基本上,當事件mouseup發生時,我想觸發另一個組件中的函數。當鼠標移動時調用其他子組件中的函數

此圖片顯示了我想要做的事:

enter image description here

我米,react-redux工作,所以我想要做的事情是當mouseup事件在child_2 component和發生這種情況時派遣行動派遣應在child_1 component內觸發另一項操作。

有人知道如何解決這個問題嗎?

回答

1

不確定終極版,但最好應如何它的工作是,國家需要通過父傳達。因此,如何實現它如下所示:

  1. 調用child_1組件中關於更改道具值(例如「flag1」)的函數。
  2. 每當出現mouseup事件時,通過child_2組件中的函數調用更新父組件中的此flag1值。

例子:

class Child1 extends React.Component { 

    ...... 
    Based on props.flag value do whatever you want 
    ...... 

} 

class Child2 extends React.Component { 

...... 
call this.props.updateStatus on mouseUp with argument 
...... 

} 

class Parent extends React.Component { 
    updateStatus(status) { 
     this.state.flag=status; 
    } 

    render() { 

     <Child1 flag={this.state.flag}> 
     </Child1> 

     <Child2 updateStatus={this.updateStatus.bind(this)> 
     </Child2> 
    } 

} 

希望有所幫助。

+0

很好用,謝謝你的幫助 – C00kieMonsta

0

你應該能夠做這樣的事情:

class Child1 extends React.Component { 
    .... 
    someFunction =() => { 

    }; 
    ... 
}; 

const Child2 = ({ onClick }) => { 
    return (<div onClick={onClick}>click me!</div>); 
}; 

class Parent extends React.Component { 
    constructor(props) { 
     super(props); 

     this.child1Ref = null; 
    } 

    render() { 
     return (<div> 
      <Child1 ref={(c) => { this.child1Ref = c; } /> 
      <Child2 
       onClick={() => { 
        if (this.child1Ref) { 
         this.child1Ref.someFunction(); 
        } 
       }); 
      /> 
     </div>); 
    } 
} 
+0

感謝您的幫助,我沒有嘗試這種方法,但看到了類似的做法。然而,使用Typescript,使用refs會變得更加複雜...以及這是我認爲的 – C00kieMonsta

相關問題