Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用REF反应父母和孩子之间的沟通_Javascript_Reactjs - Fatal编程技术网

Javascript 使用REF反应父母和孩子之间的沟通

Javascript 使用REF反应父母和孩子之间的沟通,javascript,reactjs,Javascript,Reactjs,我有两个功能组件: function Parent(){ const child = useRef(null); async function handleSubmit(){ child.current.showAlert()) } return ( <form> <Child ref={child}> </Child> <button typ

我有两个功能组件:

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();
    }
}
函数父函数(){
const child=useRef(null);
异步函数handleSubmit(){
child.current.showAlert())
}
返回(
)
}
函数子(){
函数showAlert(){
警惕();
}
}


为什么我不能访问
子组件的函数?

您必须转发ref并修改它的值,但您没有这样做:

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

  React.useImeperativeHandle(ref, () => ({ showAlert }), [])
  // ... JSX
})
阅读更多关于