53
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Reactでinputを扱う

Last updated at Posted at 2016-06-28

Reactでinputを扱う(TypeScript版)という改訂版を書きました。


input要素をReactで使うとReactがinputを自分でコントロールするので注意が必要。

var React = require('react');
var ReactDOM = require('react-dom');

var App = React.createClass({
    render: function() {
        return (
            <div>
                <label>value a</label>
                <input type="radio" name="aradio" value="A" checked="checked" /> <br />
                <label>value b</label>
                <input type="radio" name="aradio" value="B" />
                <hr />
                <label>text input</label>
                <input type="text" name="atext" value="" />
            </div>
        )
    }
});

このようにするとラジオボタンの操作はできないしテキストの入力もできない。input要素のvalue属性はstateを通して操作する必要がある。

var App = React.createClass({
    getInitialState: function() {
        return {
            radio: "a",
            text: ""
        }
    },
    render: function() {
        return (
            <div>
                <label>value a</label>
                <input type="radio" name="aradio" value="A" checked={this.state.radio === 'a'}
                       onChange={() => this.setState({radio: 'a'})}/> <br />
                <label>value b</label>
                <input type="radio" name="aradio" value="B" checked={this.state.radio === 'b'}
                       onChange={() => this.setState({radio: 'b'})}/> 
                <hr />
                <label>text input</label>
                <input type="text" name="atext" value={this.state.text}
                       onChange={(e) => this.setState({text: e.target.value})}/>
            </div>
        )
    }
});

このようにonChangeにおいてハンドラを記述し,その中でthis.setStateを使ってthis.stateを書き直す形になる。

53
34
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?