【问题标题】:React forwardRef meaningReact forwardRef 含义
【发布时间】:2019-11-07 03:33:34
【问题描述】:

我不明白这是什么意思:

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

如果我能做到:

function FancyButton(props) {
  return (
    <button className="FancyButton" ref={props.ref}>
      {props.children}
    </button>
  );
}

【问题讨论】:

  • 您应该在父组件中 createRef 并使用 forwardRef 将其链接到子组件中

标签: javascript node.js reactjs ecmascript-6


【解决方案1】:

来自文档

引用转发是一种自动传递引用的技术 一个子组件的组件。

Ref 转发是一项可选功能,它允许某些组件获取 ref 他们收到,并进一步向下传递(换句话说,“转发” 它)给一个孩子。

关于你的问题

我不明白这是什么意思:如果我能做到:。

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

例子

// EmailInput wraps an HTML `input` and adds some app-specific styling.
const EmailInput = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} type="email" className="AppEmailInput" />
));

class App extends Component {
  emailRef = React.createRef();

  render() {
    return (
      <div>
        <EmailInput ref={this.emailRef} />
        <button onClick={() => this.onClickButton()}>
          Click me to focus email
        </button>
      </div>
    );
  }

  // `this.emailRef.current` points to the `input` component inside of EmailInput,
  // because EmailInput is forwarding its ref via the `React.forwardRef` callback.
  onClickButton() {
    this.emailRef.current.focus();
  }
}

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

您可以在here阅读更多内容

【讨论】:

  • 在我看来,forwardRef 是必需的,因为只有一些低级元素的反应组件上没有 this.props.ref,功能组件上也没有。但我认为它一直有效。
  • @TonyNgo,那篇文章内容丰富,正是我想要的。有趣的是,官方文档没有提到将 refs 作为普通道具传递,但听起来这实际上比使用 forwardRef 还好(如果不是更好)。
猜你喜欢
  • 2022-12-01
  • 2020-05-28
  • 2021-01-07
  • 2021-06-14
  • 1970-01-01
  • 2021-02-23
  • 2022-12-31
  • 2021-04-10
  • 2020-06-21
相关资源
最近更新 更多