子组件的参数怎么传给父组件
时间: 2023-11-29 14:46:56 浏览: 32
子组件向父组件传递参数需要使用回调函数的方式。具体步骤如下:
1. 在父组件中定义一个函数,用于接收子组件传递的参数。
2. 将该函数作为props传递给子组件。
3. 在子组件中,通过this.props调用父组件传递的函数,并将参数作为参数传递给该函数。
以下是一个示例代码:
父组件:
```javascript
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
message: ''
};
this.handleCallback = this.handleCallback.bind(this);
}
handleCallback(childData) {
this.setState({ message: childData });
}
render() {
return (
<div>
<ChildComponent callback={this.handleCallback} />
<p>Message from child: {this.state.message}</p>
</div>
);
}
}
export default ParentComponent;
```
子组件:
```javascript
import React, { Component } from 'react';
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
message: 'Hello from child!'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.callback(this.state.message);
}
render() {
return (
<div>
<button onClick={this.handleClick}>Send Message to Parent</button>
</div>
);
}
}
export default ChildComponent;
```
在上面的示例中,子组件通过props接收父组件传递的回调函数callback,并在点击按钮时调用该函数并传递参数。父组件中的handleCallback函数接收子组件传递的参数,并将其设置为父组件的状态值,从而实现了子组件向父组件传递参数的功能。