IT박스

React.js : 하나의 onChange 핸들러로 다른 입력 식별

itboxs 2020. 6. 28. 19:23
반응형

React.js : 하나의 onChange 핸들러로 다른 입력 식별


이것에 접근하는 올바른 방법이 무엇인지 궁금합니다.

var Hello = React.createClass({
getInitialState: function() {
    return {total: 0, input1:0, input2:0};
},
render: function() {
    return (
        <div>{this.state.total}<br/>
            <input type="text" value={this.state.input1} onChange={this.handleChange} />
            <input type="text" value={this.state.input2} onChange={this.handleChange} />
        </div>
    );
},
handleChange: function(e){
    this.setState({ ??? : e.target.value});
    t = this.state.input1 + this.state.input2;
    this.setState({total: t});
}
});

React.renderComponent(<Hello />, document.getElementById('content'));

분명히 각각의 다른 입력을 처리하기 위해 별도의 handleChange 함수를 만들 수는 있지만 그리 좋지는 않습니다. 마찬가지로 개별 입력을 위해 구성 요소를 만들 수는 있지만 이와 같은 방법이 있는지 확인하고 싶었습니다.


처럼 표준 HTML 속성을 고수 제안 nameinput당신의 입력을 식별하는 요소. 또한 상태에 다른 값을 추가하여 구성 할 수 있으므로 "전체"를 상태에서 별도의 값으로 유지할 필요가 없습니다.

var Hello = React.createClass({
    getInitialState: function() {
        return {input1: 0, input2: 0};
    },
    render: function() {
        const total = this.state.input1 + this.state.input2;

        return (
            <div>{total}<br/>
                <input type="text" value={this.state.input1} name="input1" onChange={this.handleChange} />
                <input type="text" value={this.state.input2} name="input2" onChange={this.handleChange} />
            </div>
        );
    },
    handleChange: function(e) {
        this.setState({[e.target.name]: e.target.value});
    }
});

React.renderComponent(<Hello />, document.getElementById('content'));

.bind메소드를 사용하여 메소드에 대한 매개 변수를 사전 빌드 할 수 있습니다 handleChange. 다음과 같습니다.

  var Hello = React.createClass({
    getInitialState: function() {
        return {input1:0, 
                input2:0};
    },
    render: function() {
      var total = this.state.input1 + this.state.input2;
      return (
        <div>{total}<br/>
          <input type="text" value={this.state.input1} 
                             onChange={this.handleChange.bind(this, 'input1')} />
          <input type="text" value={this.state.input2} 
                             onChange={this.handleChange.bind(this, 'input2')} />
        </div>
      );
    },
    handleChange: function (name, e) {
      var change = {};
      change[name] = e.target.value;
      this.setState(change);
    }
  });

  React.renderComponent(<Hello />, document.getElementById('content'));

( total추천하는 것이기 때문에 렌더 타임에 계산되었습니다.)


onChange이벤트는 거품 ... 당신이 뭔가를 할 수 있습니다 :

// A sample form
render () {
  <form onChange={setField}>
    <input name="input1" />
    <input name="input2" />
  </form>
}

그리고 setField 메소드는 다음과 같습니다 (ES2015 이상을 사용한다고 가정합니다).

setField (e) {
  this.setState({[e.target.name]: e.target.value})
}

여러 앱에서 이와 비슷한 것을 사용하며 매우 편리합니다.


더 이상 사용되지 않는 솔루션

valueLink/checkedLink되어 사용되지 는 일부 사용자를 혼란 때문에 핵심에서이 반응한다. 최신 버전의 React를 사용하면이 답변이 작동하지 않습니다. 그러나 원하는 경우 고유 한 Input구성 요소 를 만들어 쉽게 에뮬레이션 할 수 있습니다.

기존 답변 내용 :

React의 양방향 데이터 바인딩 도우미를 사용하면 훨씬 쉽게 달성 할 수 있습니다.

var Hello = React.createClass({
    mixins: [React.addons.LinkedStateMixin],
    getInitialState: function() {
        return {input1: 0, input2: 0};
    },

    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
            <div>{total}<br/>
                <input type="text" valueLink={this.linkState('input1')} />;
                <input type="text" valueLink={this.linkState('input2')} />;
            </div>
        );
    }

});

React.renderComponent(<Hello />, document.getElementById('content'));

쉬운가요?

http://facebook.github.io/react/docs/two-way-binding-helpers.html

자신 만의 믹스 인을 구현할 수도 있습니다


다음과 같이 할 수도 있습니다 :

...
constructor() {
    super();
    this.state = { input1: 0, input2: 0 };
    this.handleChange = this.handleChange.bind(this);
}

handleChange(input, value) {
    this.setState({
        [input]: value
    })
}

render() {
    const total = this.state.input1 + this.state.input2;
    return (
        <div>
            {total}<br />
            <input type="text" onChange={e => this.handleChange('input1', e.target.value)} />
            <input type="text" onChange={e => this.handleChange('input2', e.target.value)} />
        </div>
    )
}

You can use a special React attribute called ref and then match the real DOM nodes in the onChange event using React's getDOMNode() function:

handleClick: function(event) {
  if (event.target === this.refs.prev.getDOMNode()) {
    ...
  }
}

render: function() {
  ...
  <button ref="prev" onClick={this.handleClick}>Previous question</button>
  <button ref="next" onClick={this.handleClick}>Next question</button>
  ...
}

@Vigril Disgr4ce

When it comes to multi field forms, it makes sense to use React's key feature: components.

In my projects, I create TextField components, that take a value prop at minimum, and it takes care of handling common behaviors of an input text field. This way you don't have to worry about keeping track of field names when updating the value state.

[...]

handleChange: function(event) {
  this.setState({value: event.target.value});
},
render: function() {
  var value = this.state.value;
  return <input type="text" value={value} onChange={this.handleChange} />;
}

[...]

You can track the value of each child input by creating a separate InputField component that manages the value of a single input. For example the InputField could be:

var InputField = React.createClass({
  getInitialState: function () {
    return({text: this.props.text})
  },
  onChangeHandler: function (event) {
     this.setState({text: event.target.value})
  }, 
  render: function () {
    return (<input onChange={this.onChangeHandler} value={this.state.text} />)
  }
})

Now the value of each input can be tracked within a separate instance of this InputField component without creating separate values in the parent's state to monitor each child component.


I will provide really simple solution to the problem. Suppose we have two inputs username and password,but we want our handle to be easy and generic ,so we can reuse it and don't write boilerplate code.

I.Our form:

                <form>
                    <input type="text" name = "username" onChange={this.onChange} value={this.state.username}/>
                    <input type="text" name = "password" onChange={this.onChange} value={this.state.password}/>
                    <br></br>
                    <button type="submit">Submit</button>
                </form>

II.Our constructor ,which we want to save our username and password ,so we can access them easily:

constructor(props) {
    super(props);
    this.state = {
        username: '',
        password: ''
    };

    this.onSubmit = this.onSubmit.bind(this);
    this.onChange = this.onChange.bind(this);
}

III.The interesting and "generic" handle with only one onChange event is based on this:

onChange(event) {
    let inputName = event.target.name;
    let value = event.target.value;

    this.setState({[inputName]:value});


    event.preventDefault();
}

Let me explain:

1.When a change is detected the onChange(event) is called

2.Then we get the name parameter of the field and its value:

let inputName = event.target.name; ex: username

let value = event.target.value; ex: itsgosho

3.Based on the name parameter we get our value from the state in the constructor and update it with the value:

this.state['username'] = 'itsgosho'

4.The key to note here is that the name of the field must match with our parameter in the state

Hope I helped someone somehow :)


Hi have improved ssorallen answer. You don't need to bind function because you can access to the input without it.

var Hello = React.createClass({
    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
             <div>{total}<br/>
                  <input type="text" 
                    value={this.state.input1}
                    id="input1"  
                    onChange={this.handleChange} />
                 <input type="text" 
                    value={this.state.input2}
                    id="input2" 
                    onChange={this.handleChange} />
            </div>
       );
   },
   handleChange: function (name, value) {
       var change = {};
       change[name] = value;
       this.setState(change);
   }
});

React.renderComponent(<Hello />, document.getElementById('content'));

참고URL : https://stackoverflow.com/questions/21029999/react-js-identifying-different-inputs-with-one-onchange-handler

반응형