我不确定为什么我会从受控输入切换到不受控制的输入警告。 this.state.lineItemName
在我的构造函数中定义,这似乎是我读过的其他SO问题的主要错误。
这与React的todoMVC实现非常相似。
class LineItemForm extends React.Component {
constructor(props) {
super(props);
this.state = {
newLineItem: ""
}
}
render() {
return(
<tr>
<td>
<input type="text"
onChange={this.handleChange.bind(this)}
onKeyDown={this.handleKeyDown.bind(this)}
value={this.state.newLineItem}
placeholder="Search for an item..."
autoFocus={true}
/>
</td>
</tr>
);
}
handleChange(e) {
this.setState({newLineItem: event.target.value});
}
handleKeyDown(e) {
if (e.keyCode === this.props.ENTER_KEY_CODE || e.keyCode === this.props.TAB_KEY_CODE) {
e.preventDefault();
let name = e.target.value.trim();
if (name) {
let lineItem = {
name: name
};
this.props.createLineItem(lineItem, this.props.sectionId)
this.setState({newLineItem: ""})
}
} else {
return;
}
}
}
LineItemForm.defaultProps = {
ENTER_KEY_CODE: 13,
TAB_KEY_CODE: 9
}
答案 0 :(得分:2)
use
handleChange(event) {
this.setState({newLineItem: event.target.value});
}
instead of
handleChange(e) {
this.setState({newLineItem: event.target.value});
}
答案 1 :(得分:1)
The warning occurs because of an error in the handler for the onChange
event.
Controlled components require a handler for the onChange
event. This allows the component to update its value. If the handler does not work, the value
cannot be updated via the props and must be set via the value entered by the user.
To fix this error, you'll need to correct the error in the onChange
event handler you defined:
// Parameter was renamed to 'event' to reflect its use in the
// 'setState' method call below
handleChange(event) {
this.setState({newLineItem: event.target.value});
}