【问题标题】:How to call child function from Parent react hook如何从父反应钩子调用子函数
【发布时间】:2021-04-26 08:46:02
【问题描述】:

在我的父组件中我有一个对话框,在对话框的内容中我加载了子组件

这是 parent 组件中的Dialog

<Dialog
    open={open}
    onClose={handleClose}
>
    <DialogContent>
        <DialogContentText >
            <Child id={id} status={status}/>
        </DialogContentText>
    </DialogContent>
    <DialogActions>
        <Button onClick={handleClose} />
        <Button onClick={handleAcceptClose} />
    </DialogActions>
</Dialog>

在我的子组件中我有sayhi 方法

const sayhi = () => {
    alert("sialaaaaaam");
}

如何使用 ref 调用 sayhi,我想使用 ref,因为我想要最小渲染

【问题讨论】:

    标签: reactjs react-hooks react-ref


    【解决方案1】:

    您需要将 ref 转发给子组件,并使用 useImperativeHandle 挂钩。

    示例Child 组件:

    const Child = React.forwardRef(
      (props, ref) => {
        const innerRef = React.useRef();
    
        const sayhi = () => alert("sialaaaaaam");
    
        useImperativeHandle(ref, () => ({
          sayhi,
        }));
    
        return (
          {/* Child JSX */}
        );   
      }
    );
    

    然后在父组件中创建并附加一个引用到Child:

    const childRef = React.useRef();
    
    ...
    
    <Child ref={childRef} id={id} status={status}/>
    

    并调用sayhi函数:

    childRef.current.sayhi();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      • 2021-05-26
      • 2021-03-19
      • 2020-09-12
      相关资源
      最近更新 更多