如何将表单数据从子组件传递到父组件
How to pass form data from child component to parent component
我想将子组件中的表单数据发送到父组件。在
我在父组件中编写的提交功能。
父组件:
handleChangeValue = (e) => {
this.setState({
[e.target.name]: e.target.value,
[e.target.value]: e.target.value
});
}
handleSubmit() {
var newObj = {
'id' : this.state.id,
'name' : this.state.name,
};
render() {
return (
<div className="App">
<UsingForm onChangeValue =
{this.handleChangeValue} handleSubmit = {this.handleSubmit}>
</UsingForm>
</div>
);
}
子组件是:
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="uname" value = {this.props.uname}
onChange={(e)=>this.props.onChangeValue(e)}></input>
</label>
<label>
ID:
<input type="text" name="id" value = {this.props.id} onChange=
{(e)=>this.props.onChangeValue(e)}></input>
</label>
<input type="button" value="Submit" onClick=
{this.props.handleSubmit} />
</form>
未在 handleSubmit()
中获取状态值,为什么?
你必须使用箭头函数绑定 handleSubmit
函数
handleSubmit = () => {
var newObj = {
'id' : this.state.id,
'name' : this.state.name,
};
或在构造函数中
constructor(props) {
...
this.handleSubmit.bind(this)
}
你必须改变
<label>
Name:
<input type="text" name="name" value = {this.props.name}
onChange={(e)=>this.props.onChangeValue(e)}></input>
</label>
和
<UsingForm onChangeValue =
{this.handleChangeValue} handleSubmit = {this.handleSubmit} name={this.state.name} id={this.state.id}>
</UsingForm>
我想将子组件中的表单数据发送到父组件。在 我在父组件中编写的提交功能。 父组件:
handleChangeValue = (e) => {
this.setState({
[e.target.name]: e.target.value,
[e.target.value]: e.target.value
});
}
handleSubmit() {
var newObj = {
'id' : this.state.id,
'name' : this.state.name,
};
render() {
return (
<div className="App">
<UsingForm onChangeValue =
{this.handleChangeValue} handleSubmit = {this.handleSubmit}>
</UsingForm>
</div>
);
}
子组件是:
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="uname" value = {this.props.uname}
onChange={(e)=>this.props.onChangeValue(e)}></input>
</label>
<label>
ID:
<input type="text" name="id" value = {this.props.id} onChange=
{(e)=>this.props.onChangeValue(e)}></input>
</label>
<input type="button" value="Submit" onClick=
{this.props.handleSubmit} />
</form>
未在 handleSubmit()
中获取状态值,为什么?
你必须使用箭头函数绑定 handleSubmit
函数
handleSubmit = () => {
var newObj = {
'id' : this.state.id,
'name' : this.state.name,
};
或在构造函数中
constructor(props) {
...
this.handleSubmit.bind(this)
}
你必须改变
<label>
Name:
<input type="text" name="name" value = {this.props.name}
onChange={(e)=>this.props.onChangeValue(e)}></input>
</label>
和
<UsingForm onChangeValue =
{this.handleChangeValue} handleSubmit = {this.handleSubmit} name={this.state.name} id={this.state.id}>
</UsingForm>