我有一个如下的示例类:
class UserList extends React.Component {
body = React.createRef();
componentDidMount() {
this.body.scrollTop = 100;
}
render() {
<div ref={this.body}>
...
</div>
}
}
我们需要从外部传递ref,因此我创建了另一个组件:
React.forwardRef((props, ref) => <UserList
innerRef={ref} {...props}
/>)
什么是使用此 ref 的正确方式?我应该像这样重写 class 吗:
class UserLists extends React.Component {
body = React.createRef();
componentDidMount() {
this.getRef().current.scrollTop = 100;
}
getRef() {
return (this.props.innerRef || this.body)
}
render() {
<div ref={this.getRef()}>
...
</div>
}
}
也许这是一种反模式,因为传递的引用可能不包含"current"属性(回调引用或字符串引用),那么我该如何解决这个问题?
body.current
。 - Dennis Vash