跨组件传值
context对象--上下文对象
react 组件间传递数据是通过 props 向下,是单向传递的,从父级一层一层地通过 props 地向下传递到子子孙孙,有的时候我们组件一层一层的嵌套多层,这样这种方式一层一层传递麻烦,如果想跃层传递,这就会用到 context
context:上下文对象
context很好的解决了跨组件传值的复杂度。可以快速的进行跨组件数据的传递。
想要使用context进行跨组件传值那么就要使用createContext()方法同时方法中给我们提供了两个对象:
Provider对象 生产者---->用来生产数据 Consumer对象 消费者---->用来使用数据
import React, { Component } from 'react'
// 1.创建context对象
const GlobalContext = React.createContext()
class Zia extends Component {
render() {
return (
<div>
我是第一个子组件
</div>
)
}
}
class Zib extends Component {
render() {
return (
<div>
我是第2个子组件
{/* 3.任意组件引入GlobalContext并调用context,使用GlobalContext.Consumer(消费者) */}
<GlobalContext.Consumer>
{/* 4.在回调函数中直接使用生产者的数据 */}
{
(value) => {
return <h1>{value.name}</h1>
}
}
</GlobalContext.Consumer>
</div>
)
}
}
export default class fu extends Component {
render() {
return (
// 2.在根组件件引入GlobalContext,并使用GlobalContext.Provider生产者
// 并且使用value属性传入数据
<GlobalContext.Provider value={{ name: "xixi", age: 18 }}>
<div>
我是根组件
<Zia />
<Zib />
</div>
</GlobalContext.Provider>
)
}
}
函数组件使用上下文对象
在react16.8之后新增了一个特性叫hook。其中就有一个useContext可以简化我们在函数组件中使用上下文对象的复杂度
useContext
接收一个 context 对象(React.createContext 的返回值)并返回该 context 的当前值。
可以直接获取到context对象的Consumer消费者中的数据(简化我们在使用consumer的复杂度)
在没有使用的时候跨组件传值
import React, { createContext } from 'react'
let context = createContext()
function Sun() {
return (
<div>
孙
<context.Consumer>
{
(value)=>{
return (
<h1>{value.name}</h1>
)
}
}
</context.Consumer>
</div>
)
}
function Zi() {
return (
<div>
子
<Sun></Sun>
</div>
)
}
export default function Fu() {
return (
<context.Provider value={{name:"xixi",age:18}}>
<div>
父
<Zi></Zi>
</div>
</context.Provider>
)
}
使用useContext
import React, { createContext,useContext } from 'react'
let context = createContext()
function Sun() {
// 使用useContext可以直接得到Consumer中的数据
let value=useContext(context)
return (
<div>
孙
<h1>{value.name}</h1>
</div>
)
}
function Zi() {
return (
<div>
子
<Sun></Sun>
</div>
)
}
export default function Fu() {
return (
<context.Provider value={{name:"xixi",age:18}}>
<div>
父
<Zi></Zi>
</div>
</context.Provider>
)
}