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
})
阅读更多关于