【发布时间】:2017-05-12 15:47:49
【问题描述】:
我有一个函数(onClickAddSection),当它被调用时,它应该将状态设置为空字符串,但它根本不这样做。 请看一下代码并告诉我我做错了什么谢谢。
class AddNewSectionForm extends Component {
constructor(props) {
super(props);
this.state = {
sectionName: '',
validation:false
};
this.onSectionNameChange = this.onSectionNameChange.bind(this);
this.onClickAddSection = this.onClickAddSection.bind(this);
}
onSectionNameChange(event) {
if(this.state.validation==false){
this.setState({validation:true});
}
this.setState({sectionName: event.target.value});
}
onClickAddSection(event) {
event.preventDefault();
this.props.saveSection(this.state.sectionName);
this.setState({sectionName:'',validation:false});
}
render() {
return (
<div>
<TextInput name="newSection" label="Section Name :"
onChange={this.onSectionNameChange}
value={this.state.sectionName}
error = {this.state.validation==true&& this.state.sectionName.length==0?'Enter Section Name':''}/>
<AddCloseButtons add = {this.onClickAddSection}
close = {this.props.closeCharm}
/>
</div>
);
}
}
onClickAddSection 函数不会将 sectionName 设置回 ''。
添加关闭按钮:
const AddCloseButtons = ({add,close}) => {
return (
<div className="form-group">
<button className="btn btn-primary" style={{width: '40%', border:'solid black 1px'}} onClick={add}>Add</button>
<button className="btn btn-secondary" style={{width: '40%', float: 'right',border:'solid black 1px'}} onClick={close}>Close</button>
</div>);
};
【问题讨论】:
-
您能否更具体地说明您的意思是没有改变?您是否从 console.log 中知道,或者您正在寻找的其他特定结果没有发生?
-
这里组件的重点是添加一个带名称的部分。这里我有 TextInput 组件,该组件上的 onChange 方法使用函数“onSectionNameChange”更改当前组件的状态。这很好用。但是在我添加了用户键入的名称的部分后,我将状态中的 sectionName 设置为 onClickAddSection 函数内的空字符串。这不起作用
-
在我添加部分后,它没有将状态设置回空字符串。
-
它会进入函数内部吗? AddCloseButtons 长什么样子?
-
我将组件添加到主要问题中。请看一下
标签: javascript reactjs setstate