在 React 中,组件之间的数据传递方式取决于它们的关系(父子、兄弟、跨层等)。下面是最常见的几种传值方式
一、父组件 → 子组件(最常见,用 props)
父组件通过 props 向子组件传值。
// 父组件
function Parent() {const name = '张三';return <Child userName={name} />;
}// 子组件
function Child(props) {return <div>你好,{props.userName}</div>;
}
这是单向数据流:数据只能由父传子。
二、子组件 → 父组件(用回调函数)
父组件定义函数,通过 props 传给子组件,子组件再调用它回传数据。
// 父组件
function Parent() {const handleReceive = (data) => {console.log('子组件传来的数据:', data);};return <Child onSend={handleReceive} />;
}// 子组件
function Child({ onSend }) {const sendData = () => {onSend('Hello from Child');};return <button onClick={sendData}>点击传值给父组件</button>;
}
这是 React 推荐的 自下而上通信 方式。
三、兄弟组件之间(通过共同的父组件)
让父组件作为“中转站”。
function Parent() {const [message, setMessage] = useState('');return (<><ChildA onChange={setMessage} /><ChildB msg={message} /></>);
}function ChildA({ onChange }) {return <button onClick={() => onChange('来自A的消息')}>发送给B</button>;
}function ChildB({ msg }) {return <div>收到消息:{msg}</div>;
}
数据由 A 传给父组件,再由父组件传给 B。
四、跨层级传值(Context 上下文)
使用 React.createContext() 提供全局数据。
// 创建上下文
const UserContext = React.createContext();// 顶层组件
function App() {const user = { name: '张三' };return (<UserContext.Provider value={user}><Child /></UserContext.Provider>);
}// 任意层子组件
function Child() {const user = React.useContext(UserContext);return <div>你好,{user.name}</div>;
}
Context 适合主题、语言、用户信息等“全局共享数据”。
五、全局状态管理(Redux / Zustand / Recoil 等)
适用于复杂项目、多组件共享数据。
// Redux / Zustand / Jotai / Recoil 都可以实现全局状态共享。
这类库让任意组件都能读写同一份状态。
总结
| 场景 | 推荐方式 |
|---|---|
| 父 → 子 | props |
| 子 → 父 | 回调函数 |
| 兄弟组件 | 通过父组件中转 |
| 多层级传递 | Context |
| 全局共享状态 | Redux / Zustand 等 |