简体   繁体   中英

How to call child's method from parent without using Refs?

Let's say I've a parent component A and a child B :

A :

class A {
  constructor() {
    this.state = {data: []};
  }

  handleClick = () => { 
  // api call
  // set data state to the returned value from api
  // call B's createTable method
  }

  render() {
    return(
      <div>
        <button onClick={()=> this.handleClick()}>Fetch data</button>
        <B data={this.state.data} />
      </div>
  }
}

B :

class B {
  constructor() {
    this.state = {...};
  }

  createTable = () => {
    const { data } = this.props;
    // do smth
  }

  render() {
    return(...);
  }
}

I want to call createTable method from A without using Refs .

What I've done so far is using componentDidUpdate life cycle method in B to check if data prop has changed or not, If it changed call createTable method but I want to know is this right? or there's a better way of doing it because I feel it is kinda hacky or maybe bad design.

class B {
  constructor() {
    this.state = {...};
  }

  componentDidUpdate(prevProps) {
    const { data } = this.props;
    if (data !== prevProps.data) {
      this.createTable();
    }
  }

  createTable = () => {
    const { data } = this.props;
    // do smth
  }

  render() {
    return(...);
  }
}

NOTE I don't want to use hooks either just class based component.

The following example might be useful

class Parent extends Component {
 render() {
  return (
    <div>
      <Child setClick={click => this.clickChild = click}/>
      <button onClick={() => this.clickChild()}>Click</button>
    </div>
  );
 }
}

class Child extends Component {
 constructor(props) {
    super(props);
    this.getAlert = this.getAlert.bind(this);
 }
 componentDidMount() {
    this.props.setClick(this.getAlert);
 }
 getAlert() {
    alert('clicked');
 }
 render() {
  return (
    <h1 ref="hello">Hello</h1>
  );
 }
}

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