一.函数组件context传值方法
1.在src在创建一个context.js文件
2.在context.js文件写如下代码
import React from 'react' const MyContent = React.createContext() export default MyContent
3.父组件
import React from 'react' import MyContent from '../context' import Head from "./Head" export default function index() { return ( <div> <MyContent.Provider value="张三">//要传递的值 <Head /> </MyContent.Provider> </div> ) }
4.子组件
import React,{ useContext } from 'react' import MyContent from '../context' export default function Head() { const name = useContext(MyContent)//使用usecontext接收 return ( <div> {name} </div> ) }
二.类组件context传值方法
1.在src在创建一个context.js文件
2.在context.js文件写如下代码
import React from 'react' const MyContent = React.createContext() export default MyContent
3.父组件
import React, { Component } from 'react' import Head from './Head' import MyContent from '../context' export default class index extends Component { render() { return ( <div> <MyContent.Provider value="张三"> <Head></Head> </MyContent.Provider> </div> ) } }
4.子组件
import React, { Component } from 'react' import MyContent from '../context' export default class Head extends Component { static contextType = MyContent render() { //导入创建的context 并使用静态类方法contextType接收 console.log(this.context);//张三 return ( <div> </div> ) } }
三.Consumer 函数组件,类组件都可以
类组件
1.前两步跟上面一样,创建一个context.js文件,并写下上面的代码
2.父组件
import React, { Component } from 'react' import Head from './Head' import MyContent from '../context' export default class index extends Component { render() { return ( <div> <MyContent.Provider value="张三"> <Head></Head> </MyContent.Provider> </div> ) } }
3.子组件
import React, { Component } from 'react' import MyContent from '../context' export default class Head extends Component { render() { return ( <div> <MyContent.Consumer> {name => { return <p>函数组件中的name: {name}</p> }} </MyContent.Consumer> </div> ) } }
函数组件
1.前两步跟上面一样,创建一个context.js文件,并写下上面的代码
2.父组件
import React from 'react' import MyContent from '../context' import Head from "./Head" export default function index() { return ( <div> <MyContent.Provider value="张三"> <Head /> </MyContent.Provider> </div> ) }
3.子组件
import React,{ useContext } from 'react' import MyContent from '../context' export default function Head() { return ( <div> <MyContent.Consumer> {name => { return <p>函数组件中的name: {name}</p> }} </MyContent.Consumer> </div> ) }