react 父子传值_React学习——通过模态框中的表单学习父子组件之间传值
时间: 2023-11-23 13:06:07 浏览: 175
React中父组件向子组件传值可以通过props实现,而子组件向父组件传值可以通过回调函数实现。
假设我们有一个父组件Modal,其中包含一个子组件Form,我们希望在Form表单中填写完数据后,将数据传递给Modal组件进行处理。
首先,我们在Modal组件中定义一个state,用来保存Form表单中的数据:
```javascript
class Modal extends React.Component {
constructor(props) {
super(props);
this.state = {
formData: {}
};
}
// ...
}
```
然后,在Modal组件中定义一个函数,用来接收Form组件传递的数据,并更新Modal组件的state:
```javascript
handleFormData = (data) => {
this.setState({ formData: data });
}
```
接下来,在render函数中,将handleFormData函数传递给Form组件作为props:
```javascript
render() {
return (
<div>
<Form onFormData={this.handleFormData} />
</div>
);
}
```
在Form组件中,我们通过props接收父组件传递过来的onFormData函数,并在表单提交时调用该函数将数据传递给父组件:
```javascript
class Form extends React.Component {
handleSubmit = (event) => {
event.preventDefault();
const data = {
name: event.target.name.value,
age: event.target.age.value
};
this.props.onFormData(data);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" name="name" placeholder="姓名" />
<input type="text" name="age" placeholder="年龄" />
<button type="submit">提交</button>
</form>
);
}
}
```
注意,这里我们使用了event.target来获取表单中的数据,而不是使用refs或者state来获取数据,这是因为React不推荐直接操作DOM元素。
最后,当Form表单提交后,父组件的state中就会保存表单中的数据,我们可以在Modal组件中对数据进行处理或者展示。
这就是父子组件之间传值的基本方法,通过props和回调函数,可以轻松地实现组件之间的数据传递。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)