React从另一个类ES6调用一个函数

时间:2017-03-08 14:18:03

标签: javascript function class reactjs methods

class F1 extends React.Component{
  hot(){
    alert("Hot function running");
  }
  lot(){
    let t = this;
    
      ReactDOM.render(<F2 yF={() => {
      t.hot();
    }} />,document.getElementById("b"));
  }
  render(){ 
     return (
      <button onClick={this.lot}>F1 click</button>
    );
  }
}
class F2 extends React.Component{
  constructor(props){
    super(props);
  }
  render(){
    return (
      <button onClick={this.props.yF}>F2 click</button>
    );
  }  
}

 ReactDOM.render(<F1 />,document.getElementById("a"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body> 
  
  <div id="a"></div>
  
  
  <div id="b"></div>

</body>
</html>

You can see a nice illustration here

当我点击 class F1时,我想调用Button F2内的函数来执行F1中的函数。

目前我试图将功能从F1传递到F2,但它无法正常工作

更新1

简化......

点击hot

上的按钮,我试图在F1内拨打F2个功能

1 个答案:

答案 0 :(得分:0)

您需要在constructor方法中将lot方法绑定到此方法。然后只有它才能得到上下文

class F1 extends React.Component{
  constructor() {
    super();
    this.lot = this.lot.bind(this);
  }
  hot(){
    alert("Hot function running");
  }
  lot(){              
      ReactDOM.render(<F2 yF={() => {
       this.hot();
      }} />,document.getElementById("b"));
  }
  render(){ 
     return (
      <button onClick={this.lot}>F1 click</button>
    );
  }
}
class F2 extends React.Component{
  constructor(props){
    super(props);
  }
  render(){
    return (
      <button onClick={this.props.yF}>F2 click</button>
    );
  }  
}

 ReactDOM.render(<F1 />,document.getElementById("a"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body> 
  
  <div id="a"></div>
  
  
  <div id="b"></div>

</body>
</html>