react组件如何传输值
传递 Props
父组件通过属性向子组件传递数据。子组件通过 props 接收这些值。
父组件:
<ChildComponent name="John" age={25} />
子组件:
function ChildComponent(props) {
return <div>{props.name} is {props.age} years old</div>;
}
使用 Context API
适用于跨多层级组件传递数据,避免逐层传递 props。
创建 Context:
const MyContext = React.createContext();
提供数据:
<MyContext.Provider value={{ user: 'Alice', role: 'admin' }}>
<ChildComponent />
</MyContext.Provider>
消费数据:

function ChildComponent() {
const context = useContext(MyContext);
return <div>{context.user} is {context.role}</div>;
}
回调函数传递
父组件通过回调函数接收子组件的数据。
父组件:
function ParentComponent() {
const handleData = (data) => {
console.log(data);
};
return <ChildComponent onData={handleData} />;
}
子组件:
function ChildComponent({ onData }) {
const sendData = () => {
onData('Hello from child');
};
return <button onClick={sendData}>Send Data</button>;
}
状态管理库
使用 Redux 或 MobX 等库管理全局状态,组件通过连接器或 hooks 获取数据。

Redux 示例:
import { useSelector } from 'react-redux';
function Component() {
const counter = useSelector(state => state.counter);
return <div>{counter}</div>;
}
使用 Refs
通过 ref 直接访问子组件实例或 DOM 元素,获取其值。
父组件:
function ParentComponent() {
const childRef = useRef();
const getValue = () => {
console.log(childRef.current.value);
};
return (
<>
<ChildComponent ref={childRef} />
<button onClick={getValue}>Get Value</button>
</>
);
}
子组件:
const ChildComponent = forwardRef((props, ref) => {
return <input ref={ref} defaultValue="Default" />;
});






