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

Mah*_*our 4 javascript reactjs react-native react-ref

refs用于访问子组件

<MyComponent
   ref='_my_refs'
   ...
/>
Run Code Online (Sandbox Code Playgroud)

并打电话给他们

this.refs._my_refs.scrollToTop();
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

警告:不能为函数组件提供引用。尝试访问此引用将失败。你的意思是使用 React.forwardRef() 吗?

Ven*_*sky 11

你需要MyComponent环绕React.createRef()

例如

const MyComponent = React.forwardRef((props, ref) => {
    return (
        <View ref={ref}> // using the ref
            // your component 
        </View>
})
Run Code Online (Sandbox Code Playgroud)

此外,ref='_my_refs'不起作用,它应该是React.createRef()或者如果它是一个功能组件useRef

例如

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this._my_refs = React.createRef();
    }

    render(){
        return (
            // ...
            <MyComponent
                ref={ref => this._my_refs = ref}
                ...
            />
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

或者

const ParentComponent = props => {
    const myRef = React.useRef()    
    return (
        // ...
        <MyComponent
            ref={ref}
            ...
        />
    )
}
Run Code Online (Sandbox Code Playgroud)

如果你将 a 传递ref给一个功能组件并且它没有被包裹React.forwardRef,它会给你错误

警告:不能为函数组件提供引用。尝试访问此引用将失败。你的意思是使用 React.forwardRef() 吗?

这意味着MyComponent是一个功能组件,而不是围绕React.forwardRef.