こんな感じで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で管理するようにしてcomponentWillReceiveProps
でsetState
することで動くようになった。
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} />
}
});
ホントにこれでいいのかは謎。