【问题标题】:Child component function not called from parent in reactjsreactjs中未从父级调用子组件函数
【发布时间】:2021-06-28 20:37:08
【问题描述】:

我正在使用 reactjs 构建游戏。我有一个父组件,我正在尝试使用 ref 在子组件中调用一个方法,但它不起作用。有人可以帮助为什么吗? (在下面的例子中忽略大小写。)

function parent() {
    childRef = useRef()

    ...
    const someFunc = () => {
        childRef.current.childFunc()
    }
    ...
    return <Child ref={childRef} />
}

function Child() {
    ...
    const childFunc = () => {
        ... code ...
    }
    ...
}

错误:无法读取未定义的属性“childFunc”

【问题讨论】:

  • 请查看reference希望对您有所帮助!

标签: reactjs use-ref


【解决方案1】:

useImperativeHandle

我相信会是这样的:

function parent() {
    childRef = useRef()

    ...
    const someFunc = () => {
        childRef.current.childFunc()
    }
    ...
    return <Child ref={childRef} />
}

function Child(props, ref) {
    ...
    useImperativeHandle(ref, () => ({
      childFunc: () => {
        ... code ...
      }
    }));
    ...
}

Child = forwardRef(Child);

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2017-11-24
    • 1970-01-01
    • 2015-07-11
    • 2018-04-29
    相关资源
    最近更新 更多