在React中,组件间的通信可以通过以下几种方式实现:
父子组件通信:
// 父组件
function ParentComponent() {
const handleChildMessage = (message) => {
console.log("Child message received:", message);
};
return (
<div>
<h1>Parent Component</h1>
<ChildComponent onMessage={handleChildMessage} />
</div>
);
}
// 子组件
function ChildComponent({ onMessage }) {
const handleButtonClick = () => {
const message = "Hello from Child Component!";
onMessage(message); // 调用回调函数向父组件传递数据
};
return (
<div>
<h2>Child Component</h2>
<button onClick={handleButtonClick}>Send Message</button>
</div>
);
}
兄弟组件通信:
// 父组件
function ParentComponent() {
const [message, setMessage] = useState("");
const handleChildMessage = (newMessage) => {
setMessage(newMessage); // 更新父组件状态中的消息
};
return (
<div>
<h1>Parent Component</h1>
<ChildComponent1 message={message} onMessage={handleChildMessage} />
<ChildComponent2 message={message} />
</div>
);
}
// 子组件(兄弟组件)
function ChildComponent1({ message, onMessage }) {
const handleButtonClick = () => {
onMessage("Hello from Child Component 1!"); // 更新父组件状态中的消息
};
return (
<div>
<h2>Child Component 1</h2>
<button onClick={handleButtonClick}>Send Message</button>
</div>
);
}