我正在尝试遵循以下处理多输入示例: https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs
我尝试添加两个表单元素firstName和lastName。一个在主render()函数中呈现,而另一个是使用名为LastName()的单独JSX函数创建的。
结果可在此处获得: https://codepen.io/sagiba/pen/Kmdrdz?editors=0010
class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2,
firstName: 'John',
lastName: 'Doe'
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
const LastName = () => {
return (
<label>
Last Name:
<input
name="lastName"
type="text"
value={this.state.lastName}
onChange={this.handleInputChange} />
</label>
);
};
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
<br />
<label>
First Name:
<input
name="firstName"
type="text"
value={this.state.firstName}
onChange={this.handleInputChange} />
</label>
<br />
<LastName />
</form>
);
}
}
ReactDOM.render(
<Reservation />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
两者都按预期呈现。但是,当尝试编辑姓氏的值时,组件将失去对每次击键的关注。 firstName不会发生这种情况。
我做错了什么?
答案 0 :(得分:3)
每当状态发生变化时,React都会重新呈现应用程序。因此,它运行重新创建姓氏组件的功能;该函数返回一些&#34; new&#34;每次。只需从功能中删除它,你就会变得金黄。
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
<br />
<label>
First Name:
<input
name="firstName"
type="text"
value={this.state.firstName}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Last Name:
<input
name="lastName"
type="text"
value={this.state.lastName}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}