LoginSignup
10
6

More than 5 years have passed since last update.

Reactで外からvalueを変更できるinput要素を作りたい

Last updated at Posted at 2015-02-16

こんな感じでpropsでデフォルトのテキストを渡せるようにしたい。

var InputBox = React.createClass({
  render: function() {
    return <input type="text" value={this.props.text} />
  }
});

しかしこれだと動かない。

理由はこちらにある通り。

reactjs - React.jsでFormを扱う - Qiita

defaultValueを使えばいいらしい。

var InputBox = React.createClass({
  render: function() {
    return <input type="text" defaultValue={this.props.text} />
  }
});

と思ってやってみたけど、propsが変更されたときに追従してくれない。

valueにしてstateで管理するようにしてcomponentWillReceivePropssetStateすることで動くようになった。

var InputBox = React.createClass({
  getInitialState: function() {
    return { text: this.props.text };
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({ text: nextProps.text });
  },
  onChange: function(e) {
    this.setState({ text: e.target.value });
  },
  render: function() {
    return <input type="text" value={this.state.text} onChange={this.onChange} />
  }
});

ホントにこれでいいのかは謎。

10
6
0

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
10
6