繁体   English   中英

使用 refs 对父子之间的通信做出反应

[英]react communication between parent and child using refs

我有 2 个功能组件:

function Parent(){
    const child = useRef(null);
    async function handleSubmit(){
       child.current.showAlert())
    }
    return (
        <form> 
            <Child ref={child}> </Child>
            <button type="button" onClick={handleSubmit}>
        </form>
    )
}

function Child(){
    function showAlert(){
        alert();
    }
}

为什么我无法访问child组件的function?

你必须转发 ref 并改变它的值,你没有这样做:

const Child = React.forwardRef((props, ref) => {
  function showAlert(){
    alert();
  }

  React.useImeperativeHandle(ref, () => ({ showAlert }), [])
  // ... JSX
})

阅读有关useImperativeHandle更多信息

暂无
暂无

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

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