反应 forwardRef 含义

luk*_*uky 7 javascript node.js ecmascript-6 reactjs

我不明白这有什么意义:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));
Run Code Online (Sandbox Code Playgroud)

如果我能做到这一点:

function FancyButton(props) {
  return (
    <button className="FancyButton" ref={props.ref}>
      {props.children}
    </button>
  );
}
Run Code Online (Sandbox Code Playgroud)

Ton*_*Ngo 4

从文件来看

\n\n
\n

引用转发是一种自动将引用通过组件传递给其子组件的技术。

\n\n

引用转发是一项可选功能,它允许某些组件获取它们收到的引用,并将其进一步向下传递(换句话说,\xe2\x80\x9cforward\xe2\x80\x9d\n)到子组件。

\n
\n\n

对于你的问题

\n\n
\n

我不明白这有什么意义:如果我能做到这一点:。

\n
\n\n

您可以选择第一种方法或第二种方法

\n\n

例子

\n\n
// EmailInput wraps an HTML `input` and adds some app-specific styling.\nconst EmailInput = React.forwardRef((props, ref) => (\n  <input ref={ref} {...props} type="email" className="AppEmailInput" />\n));\n\nclass App extends Component {\n  emailRef = React.createRef();\n\n  render() {\n    return (\n      <div>\n        <EmailInput ref={this.emailRef} />\n        <button onClick={() => this.onClickButton()}>\n          Click me to focus email\n        </button>\n      </div>\n    );\n  }\n\n  // `this.emailRef.current` points to the `input` component inside of EmailInput,\n  // because EmailInput is forwarding its ref via the `React.forwardRef` callback.\n  onClickButton() {\n    this.emailRef.current.focus();\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

对我来说,fowardRef 并不需要太多,因为我们总是可以使用另一种方法传递 ref

\n\n

您可以在这里阅读更多内容

\n

  • 在我看来,需要forwardRef,因为react组件上没有this.props.ref,仅在一些低级元素上,而且在功能组件上也没有。但我认为直到现在它都有效。 (3认同)
  • @TonyNgo,那篇文章内容非常丰富,正是我正在寻找的内容。有趣的是,官方文档没有提及将 refs 作为普通 props 传递,但听起来这实际上是比使用forwardRef 更好(如果不是更好)的做法。 (2认同)