[英]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.