[英]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.