如何在React中同时使用转发ref和内部ref

4

我有一个如下的示例类:

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
我已经修复了代码。 - nitrovatter
1个回答

1
你的代码没有意义,因为你用 .scrollTop 覆盖了引用,所以 ref={this.body} 是无用的。
但是这里有一个通用的示例,展示如何传递引用:
class UserLists extends React.Component {
  render() {
    return <div ref={this.props.innerRef}>Hello</div>;
  }
}

const Forwared = React.forwardRef((props, ref) => {
  const defaultRef = useRef();
  return <UserLists innerRef={ref || defaultRef} {...props} />;
});

const App = () => {
  const ref = useRef();
  useEffect(() => {
    console.log(ref);
  }, []);
  return <Forwared ref={ref} />;
};

Edit jovial-currying-hegmz


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接