在父类组件中使用函数组件 ref

时间:2021-06-17 18:28:11

标签: reactjs react-native components react-ref

是否可以从类组件 Child 访问函数组件 Parent 的函数和变量?

class Parent extends React.Component{
    constructor(props) {
        super(props);
        this.child = React.createRef();
    }

    hello = () => {
        this.child.current.hello()
    }

    render(){
        return(
            <div>
                ...
                <Child ref={this.child} />
                <button onClick={this.hello}
            </div>
        )
    }
}

const Child = forwardRef((props, ref) => {

  useImperativeHandle(ref, () => ({

    hello() {
      alert("hello from Child");
    }

  }));

  return <h1>Hi</h1>;
});

1 个答案:

答案 0 :(得分:1)

是的,您的实施应该有效。

你只需要改变你孩子的一件小事

const Child = React.forwardRef((props, ref) => {

  const hello = () => {
    alert('hello from child')
  }

  React.useImperativeHandle(ref, () => ({
    hello
  }))

  return <div>hi</div>
})