嘿,我正在尝试将todoValue从子级发送到父级组件, 当前,当我运行此代码时,我收到一条错误消息:“ TypeError:this.props.addNewTodo不是函数”是否有任何建议/修复?
感谢CasperTheGhost
我的代码:
父组件
class App extends Component {
constructor() {
super()
this.state = {
todos: []
}
}
addNewTodo = (newTodo) => {
this.setState({
todos: [...this.state.todos, newTodo]
})
}
render() {
return (
<div className="App" >
<AddTodo newTodo={this.addNewTodo} />
</div>
);
}
}/
子组件
class AddTodo extends Component {
constructor() {
super()
this.state = {
todoValue: ""
}
}
onSubmit = (event) => {
event.preventDefault();
const todo = this.state.todoValue;
this.props.addNewTodo(todo)
}
handleTodoValue = (event) => {
this.setState({todoValue: event.target.value})
}
render() {
return(
<form onSubmit={this.onSubmit}>
<FormControl>
<InputLabel>What Are Going Todo</InputLabel>
<Input id="todo" value={this.state.todoValue} onChange={this.handleTodoValue} required/>
{/* <Button>Add Todo</Button> */}
</FormControl>
</form>
);
};
};
答案 0 :(得分:0)
道具名称与呼叫名称不同。道具名称为newTodo
。因此,请使用newTodo
代替addNewTodo
onSubmit = (event) => {
event.preventDefault();
const todo = this.state.todoValue;
this.props.newTodo(todo)
}
答案 1 :(得分:0)
我认为您应该使用Redux或React Context:(https://reactjs.org/docs/context.html)