react组件如何传输值
父子组件传值(Props)
父组件通过props向子组件传递数据。子组件通过this.props(类组件)或直接解构props(函数组件)接收数据。
// 父组件
function Parent() {
const data = "Hello from Parent";
return <Child message={data} />;
}
// 子组件(函数式)
function Child({ message }) {
return <div>{message}</div>;
}
子向父传值(回调函数)
父组件通过props传递回调函数给子组件,子组件调用该函数将数据传回父组件。
// 父组件
function Parent() {
const handleData = (data) => {
console.log(data);
};
return <Child onSendData={handleData} />;
}
// 子组件
function Child({ onSendData }) {
return <button onClick={() => onSendData("Child data")}>Send</button>;
}
Context API跨层级传值
通过React.createContext创建上下文,Provider提供数据,Consumer或useContext消费数据。
const MyContext = React.createContext();
// 提供者
function App() {
return (
<MyContext.Provider value={"Global data"}>
<ComponentA />
</MyContext.Provider>
);
}
// 消费者(函数组件)
function ComponentA() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
状态管理工具(Redux等)
通过全局状态管理库实现任意组件间数据共享。
// 使用Redux示例
import { useSelector, useDispatch } from 'react-redux';
function Component() {
const data = useSelector(state => state.data);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: 'UPDATE', payload: newData })}>
Update
</button>
);
}
事件总线(Event Emitter)
通过自定义事件实现非父子组件通信,适用于复杂场景。
import { EventEmitter } from 'events';
const emitter = new EventEmitter();
// 组件A发射事件
emitter.emit('eventName', data);
// 组件B监听事件
useEffect(() => {
emitter.on('eventName', handleEvent);
return () => emitter.off('eventName', handleEvent);
}, []);
Refs传值
通过useRef或createRef获取DOM节点或组件实例,直接调用其方法。

function Parent() {
const childRef = useRef();
const handleClick = () => {
childRef.current.doSomething();
};
return (
<>
<Child ref={childRef} />
<button onClick={handleClick}>Trigger</button>
</>
);
}
// 子组件需使用forwardRef
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
doSomething: () => console.log('Called from parent')
}));
return <div>Child</div>;
});






