Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - reactjs this.refs vs document.getElementById

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

By basic I mean something like:

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?

question from:https://stackoverflow.com/questions/37273876/reactjs-this-refs-vs-document-getelementbyid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...