我正在使用 reactjs 构建游戏。我有一个父组件,我正在尝试使用 ref 调用子组件中的方法,但它不起作用。有人可以帮助为什么吗? (在下面的例子中忽略大小写。)
function parent() {
childRef = useRef()
...
const someFunc = () => {
childRef.current.childFunc()
}
...
return <Child ref={childRef} />
}
function Child() {
...
const childFunc = () => {
... code ...
}
...
}
错误:无法读取未定义的属性“childFunc”
答案 0 :(得分:0)
我相信应该是这样的:
function parent() {
childRef = useRef()
...
const someFunc = () => {
childRef.current.childFunc()
}
...
return <Child ref={childRef} />
}
function Child(props, ref) {
...
useImperativeHandle(ref, () => ({
childFunc: () => {
... code ...
}
}));
...
}
Child = forwardRef(Child);