简体   繁体   English

如何在不使用 Refs 的情况下从父级调用子级的方法?

[英]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和一个子组件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 .我想从A调用createTable方法而不使用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?到目前为止我所做的是在B中使用componentDidUpdate生命周期方法来检查data道具是否已更改,如果更改则调用createTable方法但我想知道这是对的吗? or there's a better way of doing it because I feel it is kinda hacky or maybe bad design.或者有更好的方法,因为我觉得它有点 hacky 或者可能是糟糕的设计。

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.注意我不想只使用基于 class 的组件的钩子。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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