在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);
以上是幾種常見的跨組件傳值的方式,在不同的場景下選擇適合的方式來傳遞數據。