クリック時に material-ui を使用してテキスト フィールドの値を取得して、状態を更新しようとしています。ただ、ここのtodo状態の更新はsetStateが常に一歩遅れているようです。たとえば、最初に「asdf」と入力すると、this.state.todo
空になります (これが初期化されたものです)。次に「1234」と入力します。クリックすると、それthis.state.todo
が「asdf」であることがわかりました!
質問 1:これは setState の「保留中の状態遷移」と関係があると思いますが、これを解決する方法がわかりません。
バニラ (非マテリアル UI) 入力フィールドで onChange と value を使用すると、すべてうまく機能しました。
質問 2: setState が material-ui getValue() の場合にプロセスをバッチ処理した理由についても興味がありますが、入力で onChange/Value を使用した場合はそうではありません。
以下は両方の品種のコードです。
Material-UI TextField:
const Main = React.createClass({
mixins: [ReactFire],
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
todo: ''
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme
};
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
this.fb = new Firebase(rootUrl+'items/');
this.bindAsArray(this.fb,'items');
},
render() {
let containerStyle = {
textAlign: 'center',
paddingTop: '200px'
};
let standardActions = [
{ text: 'Okay' }
];
return (
<div>
<AppBar
title="Immaterial"
iconClassNameRight="muidocs-icon-navigation-expand-more" />
<div style={containerStyle}>
<TextField
hintText="Hint Text"
ref="newTodo"
/>
<Dialog
title="Go get 'em Tiger!"
actions={standardActions}
ref="superSecretPasswordDialog">
{this.state.todo}
</Dialog>
<h3>A journey of a thousand miles begins with a single step</h3>
<RaisedButton label="Carpe Diem" primary={true} onTouchTap={this._handleTouchTap} />
</div>
</div>
);
},
_handleTouchTap() {
var todo = this.refs.newTodo.getValue()
console.log(todo)
this.setState({todo: todo});
console.log(this.refs.newTodo.getValue())
console.log(this.state.todo)
// this.firebaseRefs.items.push({
// todo: this.state.todo
// });
//this.refs.superSecretPasswordDialog.show();
//this.refs.newTodo.clearValue();
}
バニラインプット
getInitialState: function() {
return {text: ''};
},
handleChange: function(event) {
//console.log(event.target.value)
this.setState({text: event.target.value})
},
handleButtonClick: function() {
//console.log(this.state.text)
this.props.itemsStore.push({
text: this.state.text,
done: false
});
this.setState({text:''});
},
render: function(){
return <div className="input-group">
<input
value = {this.state.text}
onChange = {this.handleChange}
type="text"
className = "form-control"
placeholder = "getting things done!"
/>
<span className="input-group-btn">
<button
onClick={this.handleButtonClick}
className="btn btn-default"
type="button">
Add
</button>
</span>
</div>
}