我正在使用 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/