如何使用挂钩在子组件中调用父方法(ForwardRef概念)

时间:2020-07-05 10:09:44

标签: reactjs react-hooks

我尝试了以下代码,但失败了 所以,这是我的父组件:

    import React from 'react'
import ChildComponent from './ChildComponent';

const ParentComponent = (props) => {

    //step 1
    // const inputRef = React.createRef();
    const buttonRef = React.useRef();
    const focusHandler = () => {
        alert("hi");
    }

    return (
        <div>
            {/* In parent, we generally pass reference to child which we dint do here, lets see if props children help here */}
            {props.children}
            <ChildComponent ref="buttonRef" />

        </div>
    )
}

export default ParentComponent;

这是我的孩子部分:

import React from 'react'

const ChildComponent = React.forwardRef((props, ref) => {
    return (
        <div>
            <button onClick={ref.focusHandler}>Focus Input</button>      
        </div>
    )
})

export default ChildComponent;

单击子组件上方的按钮,我希望调用Parent方法。 如何实现? 编辑

3 个答案:

答案 0 :(得分:1)

只需在父组件中将ref替换为focusHandler

<ChildComponent focusHandler={focusHandler} />

然后在ChildComponent中,也删除ref

答案 1 :(得分:1)

出现错误的原因是,需要使用ref={buttonRef}而不是ref="buttonRef"传递函数组件中的引用。类组件可以使用字符串引用来做某事,但即使在那儿也不建议这样做。

关于从父组件调用函数,您不需要引用即可执行此操作。因此,如果这是您使用裁判的唯一原因,则可以删除裁判。而是将函数作为prop传递:

const ParentComponent = (props) => {
    const focusHandler = () => {
        alert("hi");
    }

    return (
        <div>
            <ChildComponent focusHandler={focusHandler} />
        </div>
    )
}

const ChildComponent = (props) => {
    return (
        <div>
            <button onClick={props.focusHandler}>Focus Input</button>      
        </div>
    )
}

答案 2 :(得分:1)

如果您想知道在这种情况下如何使用引用(尽管这不是推荐的传递回调的方法),则需要分配focusHandler键并将引用与{ {1}},refer to Components and Props docs

ref.current

Edit blissful-leaf-emm72