Changing check value of checkbox without using setState but using ref attribute in React

时间:2017-08-04 12:02:41

标签: reactjs checkbox babeljs

I am selecting an input element using ref and then finally resetting each checked value to false(unchecking). We should be using setState but in my case its working as desired.So is there any deep drawback in doing so?

insertRow(event){
  .....
  let op,t,res='';

  for(let i=1;i<4;i++){
    op="op"+i;
    t=this.refs[op];
    res+=t.checked?t.value:'';
    t.checked=false;
  }
  .....
} 

render(){
  return(
    <div>...
      <input key="1" ref="op1" type="checkbox" value="a"/>a) Dietary Restrictions<br/>
      <input key="2"  ref="op2" type="checkbox" value="b"/>b) Physical  Disabilities<br/>
      <input key="3" ref="op3" type="checkbox" value="c"/>c) Medical Needs<br/>
    </div>
  );
}

1 个答案:

答案 0 :(得分:0)

I am selecting an input element using ref and then finally resetting each checked value to false(unchecking). We should be using setState but in my case its working as desired. So is there any deep drawback in doing so?

A couple of things about your implementation.

  1. Refs should be used as sparingly as possible. Anything that can be handled declaratively via the use of state should be per Facebook's reccommendations. see below...

Your first inclination may be to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. See the Lifting State Up guide for examples of this.

  1. You are using a deprecated method of accessing refs. The current way of doing so is as follows:

<input type="text" ref={(input) => { this.textInput = input; }} />

you can this access this ref via the following call:

this.textInput.someMethodOrProperty;


Here is a link providing best practices concerning Refs and the DOM.