我目前正在开发我的第一个全栈单页应用程序(只是一个简单的待办事项列表Web应用程序。我正在使用react。我有一个组件Add-task-form,它在用户每次单击“添加任务”按钮时都会呈现在用户单击“提交但”后,我的表单运行良好,提交后,我一直想不出一种使表单消失的方法。我有一个“成功组件”,可呈现一条消息“任务成功添加到数据库”,它也可以正确显示,但就在“添加任务表单”旁边。一旦任务成功添加到数据库中(单击提交后,我应该在哪里隐藏muy的“添加任务表单” )?任何指导将不胜感激。
这是我的添加任务表单的代码:
export class AddTaskForm extends Component {
constructor() {
super();
this.state = {
name: '',
notes: '',
timeSpent: '',
done:null
};
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
const newTask = this.state;
if (!newTask.name || isNaN(newTask.timeSpent)) {
this.setState({ error: true })
} else {
this.props.add({ ...newTask, projectId: this.props.projectId
});
this.setState({ name: '', notes: '', timeSpent: '', error:
false, done: true})
}
};
render() {
return (
<div>
<h1>Add a Task</h1>
<div className="form-fields">
<ValidatorForm onSubmit={this.handleSubmit}>
<FormControl>
<InputLabel htmlFor="name-simple">Task Name</InputLabel>
<Input
id="name"
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}
/>
</FormControl>
{this.state.error ? (
<FormHelperText error id="name-error-text">This Field is required</FormHelperText>
) : null}
</ValidatorForm>
<FormControl>
<InputLabel htmlFor="notes">Task Notes</InputLabel>
<Input
id="notes"
type="text"
name="notes"
value={this.state.notes}
onChange={this.handleChange}
/>
</FormControl>
<ValidatorForm onSubmit={this.handleSubmit}>
<FormControl>
<InputLabel htmlFor="name-simple">Time Spent</InputLabel>
<Input
id="name-simple"
type="text"
name="timeSpent"
value={this.state.timeSpent}
onChange={this.handleChange}
/>
</FormControl>
{this.state.error ? (
<FormHelperText error id="name-error-text">A number is required</FormHelperText>
) : null}
</ValidatorForm>
<ListItem>
<Button
variant="contained"
color="primary"
onClick={this.handleSubmit}
>
Submit Task
</Button>
{this.state.done && !this.state.error ? (
<div>
<Success itemName={this.state.name} sentFrom= "task" doingWhat= "added!" />
</div>
) : null}
</ListItem>
</div>
</div>
);
}
}
答案 0 :(得分:2)
您可以按照显示Success
组件的相同方式隐藏表单:
{!this.state.done && (
<ValidatorForm onSubmit={this.handleSubmit}>
{/* ... */}
</ValidatorForm>
)}