簡體   English   中英

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

[英]How to use React.forwardRef() in React Native

我正在使用refs訪問子組件

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

並打電話給他們

this.refs._my_refs.scrollToTop();

我收到以下錯誤

警告:不能為函數組件提供引用。 嘗試訪問此引用將失敗。 你的意思是使用 React.forwardRef() 嗎?

您需要將MyComponent包裹在React.createRef()周圍

例如

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

此外, 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}
                ...
            />
        )
    }
}

或者

const ParentComponent = props => {
    const myRef = React.useRef()    
    return (
        // ...
        <MyComponent
            ref={ref}
            ...
        />
    )
}

如果你將一個ref傳遞給一個功能組件並且它沒有包裹在React.forwardRef周圍,​​它會給你錯誤

警告:不能為函數組件提供引用。 嘗試訪問此引用將失敗。 你的意思是使用 React.forwardRef() 嗎?

這意味着MyComponent是一個功能組件,並沒有包裹在React.forwardRef周圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM