javascript - 如何在 React Native 中使用 React.forwardRef()

标签 javascript reactjs react-native react-ref

我正在使用 refs用于访问子组件

<MyComponent
   ref='_my_refs'
   ...
/>

并调用他们
this.refs._my_refs.scrollToTop();

我收到以下错误

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

最佳答案

您需要包装 MyComponent React.forwardRef()
例如

const MyComponent = React.forwardRef((props, ref) => {
    return (
        <View ref={ref}> // using the ref
            // your component 
        </View>
})
另外,ref='_my_refs'不起作用,因为它是 legacy ref , 你应该使用 React.createRef() 对于类组件或 useRef 为功能组件。
您可以在 docs 中查看更多详细信息.
例如
class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this._my_refs = React.createRef();
    }

    render(){
        return (
            // ...
            <MyComponent
                ref={this._my_refs}
                ...
            />
        )
    }
}
或者
const ParentComponent = props => {
    const myRef = React.useRef()    
    return (
        // ...
        <MyComponent
            ref={myRef}
            ...
        />
    )
}
如果您通过 ref到一个功能组件,它没有被包裹 React.forwardRef ,它会给你错误

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?


这意味着 MyComponent是一个功能组件,没有被 React.forwardRef 包裹起来。 .

关于javascript - 如何在 React Native 中使用 React.forwardRef(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59948615/

相关文章:

reactjs - 如何在reactjs中使用azure ad应用身份验证2因素?

reactjs - React Native UI 组件方法

javascript - 如何在 native react 中每秒生成一次随机数?

ios - 使用 react-native 设置选择器的高度

javascript - localStorage 的设置值是否有副作用?

react-native - 默认情况下,react-navigation v3 中标题后退按钮不起作用

javascript - ExternalInterface.call() 没有得到返回值

javascript - 日韩字符显示不好

javascript - 如何为第一个字符和字符串的其余部分定义不同的正则表达式?

javascript - 通过网络套接字公开套接字