【问题标题】:React call a function from another class ES6React 从另一个类 ES6 调用函数
【发布时间】:2017-03-08 14:18:03
【问题描述】:

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>

https://jsbin.com/poqofohiqa/edit?html,js,console,output

当我单击 Button F2 时,我想调用class F1 中的函数,应该执行F1 中的函数。

目前我正在尝试将函数从 F1 传递到 F2 但它不起作用

更新 1

为了简单...

我试图通过单击F2 上的按钮在F1 中调用hot 函数

【问题讨论】:

  • ReactDOM.render 要求什么?
  • lot 函数不应该做它实际做的事情(调用ReactDOM.render)。您应该在组件之外执行此操作。
  • 它似乎有效。单击 F1 按钮会添加 F2 按钮。单击 F2 按钮会触发警报。
  • 是的 - 它正在工作。你是什​​么意思它不起作用?
  • 我不清楚所有这段代码应该做什么。

标签: javascript function class reactjs methods


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多