本文介绍了reactjs this.refs vs document.getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只有一个基本表单,我是否还应该 this.refs 或者只使用 document.getElementById

If I have just a basic forms, should I still this.refs or just go with document.getElementById?

基本上我指的是:

export default class ForgetPasswordComponent extends React.Component {
  constructor(props) {
    super(props);

    this.handleSendEmail = this.handleSendEmail.bind(this);
  }

  handleSendEmail(e) {
    e.preventDefault();

    // this.refs.email.value
    // document.getElementById('email').value
  }

  render() {
    <form onSubmit={this.handleSendEmail}>
      <input id="email" ref="email" type="text" />
      <input type="submit" />
    </form>
  }
}

使用其中一个是否有不利之处?

Is there a downside into using one over the other?

推荐答案

一般来说, refs 优于 document.getElementById ,因为它更符合您的反应代码的其余部分。

In general, refs is better than document.getElementById, because it is more in line with the rest of your react code.

在反应中,每个组件类都可以有多个组件实例。

和@Isuru在评论中指出:使用 id 很危险,因为react不会阻止你在1页上有多个表单,然后你的DOM包含多个具有相同ID的输入。这是不允许的。

In react, every component class can have multiple component instances.
And as @Isuru points out in comments: using id is dangerous, because react does not prevent you to have multiple forms on 1 page, and then your DOM contains multiple inputs with same ID. And that is not allowed.

使用refs的另一个好处是,在设计中,你只能在定义它的上下文中访问refs。如果你需要在这个上下文之外访问信息,这会强制你使用props和state(以及可能的商店)。

这是一个优点,因为你很少/没有机会打破你的单向数据流,这将使你的代码不易管理。

Another advantage to using refs, is that by design, you can only access the refs in the context where you define it. This forces you to use props and state (and possibly stores) if you need to access info outside of this context.
And this an advantage, because there is less/ no chance of you breaking your unidirectional data flow, which would make your code less manageable.

注意:几乎在所有情况下,refs都可以完全避免。根据Steve McGuire(Netflix的高级用户界面工程师)在(9:58m进入视频)。

在你的例如,这意味着将电子邮件输入值置于表单状态,添加onChange处理程序,并使用提交事件中的状态值。

NB: In almost all cases, refs can be avoided altogether. It is a design principle for Netflix to use no refs, ever, as explained by Steve McGuire (Senior User Interface Engineer at Netflix) in this video from reactjs conf 2016 (9:58m into the video).
In your case, this would mean putting the email-input value in state of the form, add on onChange handler, and use the state value in the submit event.

这篇关于reactjs this.refs vs document.getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 21:50