How to achieve passing values between React components?

There are various ways to achieve cross-component communication in React, below are several common methods:

  1. 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>;
}
  1. type of context
  2. utilize the context
// 创建一个上下文对象
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>;
}
  1. link
  2. Choose/Use Selector
// 安装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);

The above are several common ways to pass data between components, choose the appropriate method for different scenarios.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds