我有以下反应组件
class RegistrationForm extends React.Component {
constructor(props) {
super(props)
this.state = {registration: {firstName: "", lastName: "", activity: "", restrictions: ""}}
}
handleFirstNameChange(event) {
var newRegistration = Object.assign({}, this.state.registration, {firstName: event.target.value})
this.setState({registration: newRegistration})
}
handleLastNameChange(event) {
var newRegistration = Object.assign({}, this.state.registration, {lastName: event.target.value})
this.setState({registration: newRegistration})
}
handleActivitySelect(newAct) {
var newRegistration = Object.assign({}, this.state.registration, {activity: newAct})
this.setState({registration: newRegistration})
}
handleRestrictionsSelect(restrictions) {
var newRegistration = Object.assign({}, this.state.registration, {restrictions: restrictions})
this.setState({registration: newRegistration})
}
saveRegistration() {
this.props.handleChange(this.state.registration)
this.setState({registration: {firstName: "", lastName: "", activity: "", restrictions: ""}}, () => {
console.log(this.state.registration)
})
}
render() {
var style = {
padding: "15px 60px"
}
return (
<div>
<div>
<label> First Name:
<input type="text" id="firstname" onChange={this.handleFirstNameChange.bind(this)}/>
</label>
</div>
<div>
<label> Last Name:
<input type="text" id="lastname" onChange={this.handleLastNameChange.bind(this)} />
</label>
</div>
<RegistrationActivity handleChange={this.handleActivitySelect.bind(this)} activities={["Science Lab", "Swimming", "Cooking", "Painting"]} />
<RegistrationSpecialNeeds handleChange={this.handleRestrictionsSelect.bind(this)} restrictions={[{key: "a", name: "Dietary Restrictions"}, {key: 'b', name: 'Physical Disabilities'}, {key: 'c', name: 'Medical Needs'}]} />
<button style={style} onClick={this.saveRegistration.bind(this)}>Submit</button>
</div>
)
}
}
保存注册方法按预期工作。它调用在this.props.handleChange。
中传递的父方法该代码还会打印以下内容
[Log] {firstName: "", lastName: "", activity: "", restrictions: ""} (Registration.html, line 350)
所以它确实消除了注册状态。
但是在UI中我仍然可以看到填充的值。 (所以没有消失。
我有两个问题
在上面的代码中,两个文本框的内容直接与状态相关联,当状态消隐时,两个文本框(名字和姓氏)应该已经消隐
两个子组件,RegistrationSpecialNeeds和RegistrationActivity。如何通知他们应重置内部状态?
答案 0 :(得分:1)
您的问题的答案:
文本框不是受控制的组件。您只是选择了值,因为您已经了解了更改事件。您需要将值绑定到组件的状态。
<input type="text" id="firstname" value={this.state.firstName} onChange={this.handleFirstNameChange.bind(this)}/>
在此处阅读有关受控组件的内容:https://reactjs.org/docs/forms.html