子组件的表单值传给父组件
时间: 2023-09-12 19:03:07 浏览: 78
在React中,子组件向父组件传递数据通常需要使用回调函数。具体步骤如下:
1. 在父组件中定义一个回调函数,用于接收子组件传递的数据。
```javascript
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
formValue: ''
};
this.handleFormChange = this.handleFormChange.bind(this);
}
handleFormChange(value) {
this.setState({ formValue: value });
}
render() {
return (
<div>
<ChildComponent onFormChange={this.handleFormChange} />
<p>Form value: {this.state.formValue}</p>
</div>
);
}
}
```
2. 在子组件中触发父组件的回调函数,并将表单值作为参数传递。
```javascript
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.props.onFormChange(event.target.value);
}
render() {
return (
<form>
<label>
Form input:
<input type="text" onChange={this.handleInputChange} />
</label>
</form>
);
}
}
```
在上面的代码中,`ChildComponent` 中的 `handleInputChange` 方法中触发了父组件的回调函数 `onFormChange`,并将输入框中的值作为参数传递。在父组件中,`handleFormChange` 方法接收到子组件传递的值,并更新 `formValue` 的状态。最终,`ParentComponent` 中的 `render` 方法中会渲染出当前表单值。
阅读全文
相关推荐















