我想我错过了一些但不知道它是什么,我知道value = {this.text}将绑定状态的值,但由于这是内联编辑,我想用其现有值填充输入字段而不是空白。
http://jsbin.com/fugowebovi/1/edit
class TodoItem extends React.Component {
constructor(){
super()
this.state = {
text: '',
isEditing: false
};
this.onClickEdit = this.onClickEdit.bind(this);
this.onSaveEdit = this.onSaveEdit.bind(this);
this.onTextChanged = this.onTextChanged.bind(this);
}
onClickEdit(){
this.setState({isEditing: !this.state.isEditing});
}
onSaveEdit(){
this.setState({
text: this.state.text,
isEditing: false
});
}
onTextChanged(e){
this.setState({text: e.target.value});
}
render(){
return(
<li>
{this.state.isEditing ? '' : <span>{this.props.item}</span>}
{this.state.isEditing ? <span><input value={this.props.item} type="text" onChange={this.onTextChanged}/></span> :''}
{this.state.isEditing ? '' : <button onClick={this.onClickEdit}>Edit</button>}
<button onClick={this.onSaveEdit}>Save</button>
</li>
)
}
}
现在问题是它阻止了按键。
答案 0 :(得分:0)
将<input value={this.props.item} type="text" onChange={this.onTextChanged}/>
更改为
<input value={this.state.text} type="text" onChange={this.onTextChanged}/>
在构建受控组件时,应该为其提供当前文本作为值。见Controlled component in the docs
答案 1 :(得分:0)
您使用props的值并更改本地状态的值。这就是输入值没有改变的原因
试试这个:
class TodoItem extends React.Component {
constructor(props){
super()
this.state = {
text: props.item,
isEditing: false
};
this.onClickEdit = this.onClickEdit.bind(this);
this.onSaveEdit = this.onSaveEdit.bind(this);
this.onTextChanged = this.onTextChanged.bind(this);
}
onClickEdit(){
this.setState({isEditing: !this.state.isEditing});
}
onSaveEdit(){
this.setState({
isEditing: false
});
}
onTextChanged(e){
this.setState({text: e.target.value});
}
render(){
return(
<li>
{this.state.isEditing ? '' : <span>{this.state.text}</span>}
{this.state.isEditing ? <span><input value={this.state.text} type="text" onChange={this.onTextChanged}/></span> :''}
{this.state.isEditing ? '' : <button onClick={this.onClickEdit}>Edit</button>}
<button onClick={this.onSaveEdit}>Save</button>
</li>
)
}
}