react多级组件间如何传递props

1.使用props属性一级级传递
针对父,子,孙子,如何实现将props从父级传递给孙子。
父:

<ParentComponent parent={this} /> //传递this

子:

<childComponent propsContext={this.props.parent} />

孙子:

getProps() {
	return this.props.propsContext  //使用父组件传递来的props
}

2.使用API Context
使用 Context 可以更方便地跨多层级组件传递数据,而不需要手动逐层传递 props。
使用方法:
1)创建 Context

首先,需要在一个单独的文件中创建 Context 对象。

// MyContext.js
import React from 'react';

const MyContext = React.createContext();
export default MyContext;

2)提供数据的组件

在一个父组件中使用 MyContext.Provider 提供数据。

// ParentComponent.js
import React from 'react';
import MyContext from './MyContext';

class ParentComponent extends React.Component {
  render() {
    const someData = "Hello from Context";

    return (
      <MyContext.Provider value={someData}>
        {this.props.children}
      </MyContext.Provider>
    );
  }
}

export default ParentComponent;

3)接收数据的组件

这种方法只适用于单个 Context,并且只能在类组件中使用, 使用 contextType 可以让 this.context 直接获取到 Context 的值,但是这个类只能订阅一个 Context。

(如果有多个 Context 需要在同一个类组件中使用,可以通过多次使用 MyContext.Consumer 或者多个 contextType 静态属性来处理每个 Context 的值)

import React from 'react';
import MyContext from './MyContext';

class ChildComponent extends React.Component {
  static contextType = MyContext;

  render() {
    const value = this.context;

    return (
      <div>
        <p>{value}</p>
      </div>
    );
  }
}

export default ChildComponent;

相关推荐

  1. react多级组件如何传递props

    2024-07-12 21:20:05       20 阅读
  2. ReactReact中将 Props 传递组件

    2024-07-12 21:20:05       37 阅读
  3. React中的Props传递数据与组件通信

    2024-07-12 21:20:05       53 阅读
  4. day04--react中批量传递props

    2024-07-12 21:20:05       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 21:20:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 21:20:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 21:20:05       57 阅读
  4. Python语言-面向对象

    2024-07-12 21:20:05       68 阅读

热门阅读

  1. self_attention python代码

    2024-07-12 21:20:05       19 阅读
  2. pytorch 指定GPU设备

    2024-07-12 21:20:05       22 阅读
  3. C#-反射

    C#-反射

    2024-07-12 21:20:05      15 阅读
  4. Codeforces Round #956 (Div. 2) and ByteRace 2024 A-C题解

    2024-07-12 21:20:05       23 阅读
  5. 科技与狠活

    2024-07-12 21:20:05       19 阅读
  6. 大语言模型系列-Transformer

    2024-07-12 21:20:05       21 阅读
  7. Git-Updates were rejected 解决

    2024-07-12 21:20:05       20 阅读
  8. 推荐系统中的冷启动问题及其解决方案

    2024-07-12 21:20:05       18 阅读