在下面的代码中,当我更改输入中的文本时,它会错误地更新输入值,但是当我按Enter键时,数据会在两个ul
标记中更新。知道我做错了吗?
<script type="text/jsx">
/** @jsx React.DOM */
var todoList = React.createClass({
render : function(){
var createItem = function(itemText , idx){
return <li key={idx+itemText} >{itemText}</li>
};
return <ul>{this.props.itemlist.map(createItem)}</ul>
}
});
var todoApp = React.createClass({
getInitialState: function() {
return {items: [], text: ''};
},
handleChange:function(name ,e){
this.state.text = e.target.value;
this.setState({ name : e.target.value });
},
handleKeyDown : function(e , idx){
if( e.keyCode == 13 ){
var nextItems = this.state.items.concat([this.state.text]);
this.setState({ items : nextItems , text : '' });
}
},
render :function(){
var results = this.props.items;
return (
<div>
{results.map(function(idx ,item){
this.state.items[idx] = item;
return (
<div key={'outer'+idx}>
<todoList itemlist={this.state.items} />
<input key={idx} onChange={this.handleChange.bind(this, item)} onKeyDown={this.handleKeyDown} onSubmit={this.handleSubmit} />
</div>
);
} , this)}
</div>
);
}
});
React.renderComponent(<todoApp items={['item1','item2']} />, document.getElementById('example') );
</script>
答案 0 :(得分:0)
你有'名字'作为关键,但它应该是'文字'。
handleChange:function(name ,e){
this.state.text = e.target.value;
this.setState({ text : e.target.value });
},
您还需要将值传递给输入:
<input key={idx} onChange={this.handleChange.bind(this, item)}
onKeyDown={this.handleKeyDown} onSubmit={this.handleSubmit}
value={this.state.text} />