在 React 中,组件通信的方式主要取决于组件之间的层级关系。下面按常见场景系统讲一下(以 函数组件 + Hooks 为主,也提一下 class 思想)。
父组件通过属性把数据传给子组件。
function Parent() {
const msg = "hello child";
return <Child message={msg} />;
}
function Child({ message }) {
return <div>{message}</div>;
}
✅ 适用于:
function Parent() {
const getData = (val) => {
console.log("子组件说:", val);
};
return <Child onSend={getData} />;
}
function Child({ onSend }) {
return <button onClick={() => onSend("hi")}>发送</button>;
}
✅ 本质:props 传函数
把共享状态放到共同的父组件。
function Parent() {
const [value, setValue] = useState("");
return (
<>
<BrotherA onChange={setValue} />
<BrotherB value={value} />
</>
);
}
见下文。
const UserContext = createContext();
function Grandpa() {
return (
<UserContext.Provider value="Tom">
<Father />
</UserContext.Provider>
);
}
function Child() {
const name = useContext(UserContext);
return <div>{name}</div>;
}
✅ 适合:
❌ 不适合高频变化数据
适合:
const useStore = create((set) => ({
count: 0,
inc: () => set(s => ({ count: s.count + 1 }))
}));
原子化状态管理
const childRef = useRef();
<Child ref={childRef} />
childRef.current.doSomething();
✅ 慎用(破坏单向数据流)
// 简单事件中心
const bus = new EventTarget();
bus.dispatchEvent(new Event("refresh"));
❌ React 不推荐
| 场景 | 推荐方式 |
|---|---|
| 父子 | props |
| 子父 | 回调函数 |
| 兄弟 | 状态提升 |
| 跨层 | Context |
| 全局 | Redux / Zustand |
| 命令调用 | ref |
如果你愿意,可以告诉我:
我可以直接帮你写对应代码模板。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。