Context 跨组件传值方法

Context 跨组件传值方法

在这里插入图片描述

app.js
import React from 'react';
// import logo from './logo.svg';
import './App.css';
import ContextPage from './pages/ContextPage'


function App() {
  return (
    <div className="App">
      <ContextPage />
    </div>
  );
}

export default App;

父组件 ContextPage.js
import React, { Component } from 'react'
// 引入子组件ContextTypePage
import ContextTypePage from './ContextTypePage'

// 第一步创建一个Context对象
// const ThemeContext = React.createContext ()
export default class ContextPage extends Component {
 constructor(props){
   super(props)
   this.state={
     theme: {
       themeColor: 'red'
     }
   }
 }
  render() {
    // 通过props传递
    // 把constructor的属性 theme 拿出来
    const { theme } = this.state
    return (
      <div>
        <h3>ContextPage</h3>
        <ContextTypePage {...theme} />
      </div>
    )
  }
}

子组件ContextTypePage.js
import React, { Component } from 'react'

export default class ContextTypePage extends Component {
  render() {
    // 通过props父组件传递给子组件
    const { themeColor } = this.props
    return (
      <div>
         <h3 className= { themeColor } >ContextTypePage</h3>
      </div>
    )
  }
}

react Context方法

contextType只能使用在class组件中,而且只能赋值一次

公共方法Context.js 作用定义一个Context对象
import React from 'react'
// 定义一个公共context 方法
export const ThemeContext = React.createContext ()
app.js
import React from 'react';
// import logo from './logo.svg';
import './App.css';
import ContextPage from './pages/ContextPage'


function App() {
  return (
    <div className="App">
      <ContextPage />
    </div>
  );
}

export default App;

contextPage.js
import React, { Component } from 'react'
// 引入子组件ContextTypePage
import ContextTypePage from './ContextTypePage'
// 引入公共的Context.js
import { ThemeContext } from '../Context'

// // 第一步创建一个Context对象
// const ThemeContext = React.createContext ()
export default class ContextPage extends Component {
 constructor(props){
   super(props)
   this.state={
     theme: {
       themeColor: 'red'
     }
   }
 }
  render() {
    // // 通过props传递
    // 把constructor的属性 theme 拿出来
    const { theme } = this.state
    return (
      <div>
        <h3>ContextPage</h3>
        {/* 第二步使用provider传递给子组件,同时通过value把值传递给子组件 */}
        <ThemeContext.Provider value= { theme }>
         <ContextTypePage  />
        </ThemeContext.Provider>
        
      </div>
    )
  }
}

ContextTypePage.js
import React, { Component } from 'react'
import {ThemeContext} from '../Context'


export default class ContextTypePage extends Component {
  static contextType = ThemeContext
  render() {
    // 定义Context
    const { themeColor } =  this.context;
    // 通过props父组件传递给子组件
    console.log("this", this)
    // 通过static拿到themeContext
    return (
      <div>
         <h3 className={themeColor}>ContextTypePage</h3>
      </div>
    )
  }
}

在render函数中打印this会出现下图结果
在这里插入图片描述

使用hook方式的useContext 实现function 组件传递Context

contextTypePage.js

useContext只能使用在function组件内,本身是一个hooks方法,可以同时导入多个赋值

import React, { Component, useContext } from 'react'
import {ThemeContext, UserContext} from '../Context'


export default class ContextTypePage extends Component {
  static contextType = ThemeContext
  render() {
    // 定义Context
    const { themeColor } =  this.context;
    // 通过props父组件传递给子组件
    console.log("this", this)
    // 通过static拿到themeContext
    return (
      <div>
         <h3 className={themeColor}>ContextTypePage</h3>
         <Child />
      </div>
    )
  }
}

// 在创建function 的子组件 不能使用class组件里面的static方法
// 可以使用hook useContext来是实现传值
function Child () {
  // 通过useContext 获取themeContext
  const themeContext = useContext(ThemeContext)
  // 同时使用多个useContext
  const userContext = useContext(UserContext)
  console.log(userContext)
  const { themeColor } = themeContext
return <div className= {themeColor}>Child组件{userContext.name}</div>
}

context.Consumer

Context.consumer只能使用在class组件中 解决contextType一次只能赋值一次的问题

app.js
import React from 'react';
// import logo from './logo.svg';
import './App.css';
import ContextPage from './pages/ContextPage'
import ConsumerPage from './pages/ConsumerPage'



function App() {
  return (
    <div className="App">
      <ContextPage />
      <ConsumerPage />
    </div>
  );
}

export default App;

ConsumerPage.js
// 使用consumer方法在class中使用多个赋值
import React, { Component } from 'react'
import {ThemeContext, UserContext} from '../Context'


export default class ConsumerPage extends Component {
  render() {
    return (
      <div>
        <h3>ConsumerPage</h3>
        {/* Consumer 内部需要用函数来解构 */}
        <ThemeContext.Consumer>
          { themeCtx=>
            <div className={themeCtx.themeColor}>
              {
                // 嵌套写UserContext.Consumer
                <UserContext.Consumer>
                  {
                    user =><div>{user.user}</div>
                  }
                </UserContext.Consumer>
              }
            </div>
          }
        </ThemeContext.Consumer>
      </div>
    )
  }
}

注意事项

1. 对象不能引入到Provider value 里面,源于react 内部比较context的是===全等但是两个相同对象是不相同 ,因此每一次都会渲染,因此把对象放入state中
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、付费专栏及课程。

余额充值