定义3个组件,组件A向组件C传递姓名,组件B向组件C传递数组爱好,组件C接收组件A和组件B传递过来的参数并显示出来
时间: 2023-11-12 15:08:40 浏览: 191
三种参数传递
下面是一个可能的实现,使用React框架:
```jsx
// 组件A
function ComponentA(props) {
const { name } = props;
return (
<div>
<button onClick={() => props.onSendName(name)}>发送姓名</button>
</div>
);
}
// 组件B
function ComponentB(props) {
const { hobbies } = props;
return (
<div>
<button onClick={() => props.onSendHobbies(hobbies)}>发送爱好</button>
</div>
);
}
// 组件C
class ComponentC extends React.Component {
constructor(props) {
super(props);
this.state = {
name: null,
hobbies: null
};
}
handleSendName = (name) => {
this.setState({ name });
};
handleSendHobbies = (hobbies) => {
this.setState({ hobbies });
};
render() {
const { name, hobbies } = this.state;
return (
<div>
<p>姓名:{name}</p>
<p>爱好:{hobbies && hobbies.join(", ")}</p>
<ComponentA name="Alice" onSendName={this.handleSendName} />
<ComponentB hobbies={["足球", "篮球", "羽毛球"]} onSendHobbies={this.handleSendHobbies} />
</div>
);
}
}
```
组件A和组件B分别接收`name`和`hobbies`属性,并在点击按钮时触发回调函数`onSendName`和`onSendHobbies`,将参数传递给父组件。组件C是父组件,接收到参数后更新`state`,并显示在页面上。
阅读全文