第10章:组件通信
简要说明
组件通信是React开发中的核心概念之一。通过组件之间的数据传递与交互,可以实现复杂的动态功能。本章将重点讲解三种常见的组件通信方式:父组件向子组件传递数据、子组件向父组件传递数据,以及兄弟组件之间的通信。
1. 父组件向子组件传递数据(Props)
在React中,父组件可以通过props向子组件传递数据。这是一种单向数据流的机制,确保数据从父组件流向子组件。
示例:父组件传递数据给子组件
父组件代码:
function ParentComponent() {
const greet = "Hello, React!";
return (
<div>
<h2>父组件</h2>
<ChildComponent greeting={greet} />
</div>
);
}
子组件代码:
function ChildComponent(props) {
return (
<div>
<h3>子组件</h3>
<p>{props.greeting}</p>
</div>
);
}
运行结果:
父组件
子组件
Hello, React!