在React中,组件间的通信是构建应用的基础。
以下是React中几种常用的组件通信方式:
1. Props(属性)
父组件向子组件通信:父组件可以通过props向子组件传递数据。子组件通过props接受来自父组件的数据。
// 父组件
function ParentComponent() {
const message = 'Hello from Parent';
return <ChildComponent message={message} />;
}
// 子组件
function ChildComponent(props) {
return <div>{props.message}</div>;
}
2. 回调函数
子组件向父组件通信:父组件可以通过props向子组件传递一个回调函数。子组件可以调用这个回调函数并传递数据回父组件。
// 父组件
function ParentComponent() {
function handleData(data) {
console.log(data);
}
return <ChildComponent onData={handleData} />;
}
// 子组件
function ChildComponent(props) {
const data = 'Some data from Child';
props.onData(data); // 调用父组件传递的回调函数,并传