react如何传参数
在 React 中传递参数的方法
React 提供了多种传递参数的方式,具体取决于组件的类型和场景。以下是常见的参数传递方法:
父子组件传递参数(Props)
父组件通过属性(props)向子组件传递参数:
// 父组件
function ParentComponent() {
const data = "Hello from Parent";
return <ChildComponent message={data} />;
}
// 子组件
function ChildComponent(props) {
return <div>{props.message}</div>;
}
使用 Context API 跨层级传递
对于多层嵌套组件,可以使用 Context 避免逐层传递:
const MyContext = React.createContext();
// 提供者组件
function App() {
return (
<MyContext.Provider value={{ user: "Alice" }}>
<Child />
</MyContext.Provider>
);
}
// 消费者组件
function Child() {
return (
<MyContext.Consumer>
{value => <div>User: {value.user}</div>}
</MyContext.Consumer>
);
}
路由参数传递
在使用 React Router 时可以通过 URL 传递参数:
// 路由配置
<Route path="/user/:id" component={UserPage} />
// 组件内获取
function UserPage({ match }) {
return <div>User ID: {match.params.id}</div>;
}
使用状态管理库(如 Redux)
对于全局状态可以通过 Redux 等状态管理工具传递:
// Action 发送数据
dispatch({ type: 'ADD_TODO', payload: 'Learn React' });
// Reducer 接收处理
function todoReducer(state = [], action) {
switch(action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
}
回调函数传递参数
子组件可以通过回调函数向父组件传递参数:
// 父组件
function Parent() {
const handleData = (data) => {
console.log('Received:', data);
};
return <Child onSendData={handleData} />;
}
// 子组件
function Child({ onSendData }) {
const sendData = () => onSendData("Child Data");
return <button onClick={sendData}>Send</button>;
}
使用自定义 Hook 共享逻辑
自定义 Hook 可以封装参数传递逻辑:
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
}
// 组件使用
function Counter() {
const { count, increment } = useCounter(0);
return (
<div>
<p>{count}</p>
<button onClick={increment}>+</button>
</div>
);
}






