我正在构建一个简单的任务列表,并在按下按钮后清除输入字段,并做出反应,将不胜感激。我已经用react扩展程序对其进行了检查,并将其添加到所需的列表中并放置了curVal,但是输入框保持不变
class App extends Component {
state = {
taskList: [],
curValue: ""
};
changeHandler = event => {
this.setState({ curValue: event.target.value });
};
newTaskHandler = () => {
const itemValue = this.state.curValue;
const clearInput = "";
this.setState({
taskList: [...this.state.taskList, itemValue],
curValue: ""
});
};
render() {
return (
<div className="App">
<h1>Task List</h1>
<TaskInput
click={this.newTaskHandler}
value={this.state.curValue}
changed={this.changeHandler}
/>
<h1>{this.curValue}</h1>
<h1>{this.taskList}</h1>
</div>
);
}
}
const TaskInput = props => {
return (
<div>
<input
type="text"
name="task"
value={props.curValue}
onChange={props.changed}
/>
<button type="submit" onClick={props.click}>
Add to your Task List{" "}
</button>
</div>
);
};
答案 0 :(得分:0)
您提供给TaskInput
的道具被命名为value
,而不是curValue
。
将props.curValue
更改为props.value
,它将按预期工作。
const TaskInput = props => {
return (
<div>
<input
type="text"
name="task"
value={props.value}
onChange={props.changed}
/>
<button type="submit" onClick={props.click}>
Add to your Task List
</button>
</div>
);
};
class App extends React.Component {
state = {
taskList: [],
curValue: ""
};
changeHandler = event => {
this.setState({ curValue: event.target.value });
};
newTaskHandler = () => {
const itemValue = this.state.curValue;
const clearInput = "";
this.setState({
taskList: [...this.state.taskList, itemValue],
curValue: ""
});
};
render() {
return (
<div className="App">
<h1>Task List</h1>
<TaskInput
click={this.newTaskHandler}
value={this.state.curValue}
changed={this.changeHandler}
/>
<h1>{this.curValue}</h1>
<h1>{this.taskList}</h1>
</div>
);
}
}
const TaskInput = props => {
return (
<div>
<input
type="text"
name="task"
value={props.value}
onChange={props.changed}
/>
<button type="submit" onClick={props.click}>
Add to your Task List
</button>
</div>
);
};
ReactDOM.render(<App />, 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>
<div id="root"></div>