react 跨组件传值方式 context上下文 redux (白话总结)

本文详细介绍了在React中实现跨组件通信的两种常见方式:使用Context上下文和Redux状态管理库。对于Context,讲解了创建、生产和消费数据的步骤;而对于Redux,则阐述了其核心概念如store、reducer、action以及如何拆分和组织代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跨组件传值方式

方式一:context上下文

使用步骤:
    1.创建文件夹context,里面创建index.js写一个组件

    2.创建上下文对象以及(对象的方式创建)他的生产者和消费者
            2-1.引进去上下文对象createContext
            2-2.创建上下文对象

  let context=createContext()

            2-3.创建生产者和消费者   

  let {Provider,Consumer}=context;

          2-4.this.props.children 表示所有的子元素
                组件里写{this.props.children}
          2-5暴露出去

export {Index,Consumer}

    3.我们需要传递数据  那么就把当前这个上下文对象的组件变成所有组件的老大
    在整体的index.js中设置  
            3-1.引用并且解构出上下文对象的组件

 import {Index} from "./context/index.js"

         3-2.让上下文对象变成所有组件的老大,在整体的index里面把App包裹起来

                <Index>
                    <App />
                </Index>,

 4.生产数据
            4-1.生产数据

                this.props.children 表示所有的子元素

                <Provider value={
  {text:"数据1",num:666}}>

                    {/* 4.this.props.children 表示所有的子元素 */}
                    {this.props.children}

                </Provider>

    总:以上全写context文件夹下的index.js文件中            

    5.消费数据(使用数据)
        说明:谁使用数据,就在谁中设置
        5-1.引用消费者


                
React跨组件有多种方式,以下是几种常见的方式: 1. 父组件向子组件递数据:通过 props 将数据递给子组件,子组件通过 this.props 访问递的数据。示例代码: ```javascript // 父组件 class Parent extends React.Component { render() { const data = 'hello'; return <Child data={data} />; } } // 子组件 class Child extends React.Component { render() { const { data } = this.props; return <div>{data}</div>; } } ``` 2. 子组件向父组件递数据:通过父组件递函数给子组件,在子组件中调用该函数来递数据。示例代码: ```javascript // 父组件 class Parent extends React.Component { constructor(props) { super(props); this.state = { data: '' }; this.handleDataChange = this.handleDataChange.bind(this); } handleDataChange(data) { this.setState({ data }); } render() { return <Child onDataChange={this.handleDataChange} />; } } // 子组件 class Child extends React.Component { constructor(props) { super(props); this.state = { data: 'hello' }; this.handleChange = this.handleChange.bind(this); } handleChange() { const { onDataChange } = this.props; const { data } = this.state; onDataChange(data); } render() { return ( <div> <button onClick={this.handleChange}>递数据</button> </div> ); } } ``` 3. 使用 ContextContext 提供了一种在组件之间共享数据的方法,避免了通过 props 层层递的复杂性。示例代码: ```javascript // 创建 Context const MyContext = React.createContext(); // 父组件 class Parent extends React.Component { render() { const data = 'hello'; return ( <MyContext.Provider value={data}> <Child /> </MyContext.Provider> ); } } // 子组件 class Child extends React.Component { render() { return ( <MyContext.Consumer> {data => <div>{data}</div>} </MyContext.Consumer> ); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值