简体   繁体   中英

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

I have two files First.js and Second.js they are not child and Parent they have a lot of functions inside them. I want to use 1 function which is inside First.js into another file 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>
    );
  }
}

On click of Solve button in need to call updateXS() there are other functions render() also present in the first file.

You need to bubble up the action to a container

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>
    );
  }
}

Then the container can handle the solving part, set a state and pass it to the children.

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>
    );
  }
}

You should keep in mind the «actions up, data down» philosophy of react and not rely on observing events like in Jquery.

The children can react based on the new state an rerender. You can also use componentWillReceiveProps to compare new props and react to it.

You can bubble up or create an utils function file and then export them. If you think is a function that you might use across your application it might be the best solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM