簡體   English   中英

需要在不導入整個組件的情況下從一個文件調用一個函數到另一個文件

[英]Need to call a function from one file to another file in react without importing whole component

我有兩個文件First.js和Second.js,它們不是子文件,而父文件則具有很多功能。 我想將First.js內的1個函數用於另一個文件Second.js。

First.js

export default Header extends React.Component{

  constructor(){
    super();
  }

  updateXS(e){
    alert('Test');
  }
}

Second.js

export default Second extends React.Component{

  constructor(){
    super();

  }
  solveVariable() {
    updateXS()// from first file
  }


  render(){
    return (
      <div className="displayinline col-md-12 ">
         <button onClick={self.solveVariable.bind(this)}>Solve</button>
      </div>
    );
  }
}

在需要調用updateXS()的“解決”按鈕上單擊時,第一個文件中還存在其他函數render()。

您需要將動作添加到容器中

export default Second extends React.Component{

  constructor(){
    super();

  }
  solveVariable() {
    this.props.handleSolveVariable();
  }


  render(){
    return (
      <div className="displayinline col-md-12 ">
         <button onClick={self.solveVariable.bind(this)}>Solve</button>
      </div>
    );
  }
}

然后,容器可以處理求解部分,設置狀態並將其傳遞給子級。

class Container extends Component {
  solveThis(e) {
    // ... calculate
    return result;
  }
  handleSolveVariable = (e) => {
    const result = this.solveThis(e);
    this.setState({result})
  }
  render() {
    return (
      <div>
        <First result={this.state.result}/>
        <Second result={this.state.result} handleSolveVariable={this.handleSolveVariable}/>
      </div>
    );
  }
}

您應該牢記“行動起來,數據減少”的反應哲學,而不要像在Jquery中那樣依賴觀察事件。

孩子們可以根據新狀態做出反應。 您還可以使用componentWillReceiveProps來比較新道具並對其做出反應。

您可以冒泡或創建一個utils函數文件,然后將其導出。 如果您認為您可以在整個應用程序中使用該功能,那么它可能是最佳解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM