我正在尝试将状态保留在我的父App组件中,并具有功能无状态子组件。我遇到的问题是onSubmit没有从我调用的表单组件中触发。 onChange确实有效,我可以从输入中获取值。此外,如果我将表单移出组件,将props更改为state,只需在App中使用onSubmit即可。我试图理解为什么会发生这种情况以及如何在有状态和无状态组件之间传递输入值?这不起作用:
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
listItemValue: props.value || '',
todoItems: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let value = event.target.value;
this.setState({
value: this.state.value,
listItemValue: value
});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<div className="App">
<h1>Todo List</h1>
<TodoListForm name="todo"
onSubmit={this.handleSubmit}
handleChange={this.handleChange}
value={this.state.listItemValue} />
<TodoList />
</div>
);
}
}
// Stateless Functional Component
const todoListForm = (props) => {
return (
<form onSubmit={props.onSubmit}>
<label htmlFor='todo-list-item'>Add a Todo</label>
<input name={props.name}
value={props.listItemValue}
onChange={props.handleChange}
type="text"
placeholder='Enter a todo ...'/>
<button
type="submit"
className='TodoListForm__Button'>add</button>
</form>
)
}
这确实有效(但我不再为我的表格使用todoListForm组件:
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
// listItemValue: props.value || '',
todoItems: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<div className="App">
<h1>Todo List</h1>
<form onSubmit={this.handleSubmit}>
<label htmlFor='todo-list-item'>Add a Todo</label>
<input name='todo'
value={this.state.value}
onChange={this.handleChange}
type="text"
placeholder='Enter a todo ...'/>
<button
type="submit"
className='TodoListForm__Button'>add</button>
</form>
<TodoList />
</div>
);
}
}