在React中,实现跨组件传值有多种方式,以下列举了几种常见的方式:
props
对象访问传递过来的值。// 父组件
import React from "react";
import ChildComponent from "./ChildComponent";
function ParentComponent() {
const data = "Hello, World!";
return <ChildComponent data={data} />;
}
// 子组件
import React from "react";
function ChildComponent(props) {
return <div>{props.data}</div>;
}
contextType
或useContext
来访问共享的数据。// 创建一个上下文对象
const MyContext = React.createContext();
// 父组件
import React from "react";
import ChildComponent from "./ChildComponent";
function ParentComponent() {
const data = "Hello, World!";
return (
<MyContext.Provider value={data}>
<ChildComponent />
</MyContext.Provider>
);
}
// 子组件
import React from "react";
function ChildComponent() {
const data = React.useContext(MyContext);
return <div>{data}</div>;
}
connect
函数或useSelector
来访问和更新数据。// 安装redux和react-redux库
npm install redux react-redux
// 创建一个Redux store
import { createStore } from "redux";
const initialState = {
data: "Hello, World!"
};
function reducer(state = initialState, action) {
switch (action.type) {
case "UPDATE_DATA":
return { ...state, data: action.payload };
default:
return state;
}
}
const store = createStore(reducer);
// 父组件
import React from "react";
import { connect } from "react-redux";
import ChildComponent from "./ChildComponent";
function ParentComponent({ data }) {
return <ChildComponent data={data} />;
}
const mapStateToProps = state => {
return {
data: state.data
};
};
export default connect(mapStateToProps)(ParentComponent);
// 子组件
import React from "react";
import { connect } from "react-redux";
function ChildComponent({ data }) {
return <div>{data}</div>;
}
const mapStateToProps = state => {
return {
data: state.data
};
};
export default connect(mapStateToProps)(ChildComponent);
以上是几种常见的跨组件传值的方式,在不同的场景下选择适合的方式来传递数据。