conntext 是react 提供的实现数据共享的api . 解决props层层传递的问题
1.React.createConntext()创建Context对象
2.使用Context Provider 包裹组件 给他的后代组件提供数据
3.Context Provider所有的后代组件,都可以通过
import React, { useState, useEffect, createContext, Component, memo, useContext } from 'react'; const CountContext = createContext(); function App2() { const [count, setCount] = useState(0); return ( <div> <CountContext.Provider value={count}> <Foo></Foo> <Bar></Bar> <Couter></Couter> </CountContext.Provider> <button onClick={() => { setCount(count + 1) }}>点击</button> </div> ) } class Foo extends Component { render() { return ( <CountContext.Consumer> { count => <h1>{count}</h1> } </CountContext.Consumer> ) } } class Bar extends Component { static contextType = CountContext; render() { let count = this.context; return ( <div>{count}</div> ) } } function Couter() { const count = useContext(CountContext) return ( <div>{count}</div> ) } export default App2;
如果没有Provider则会取默认值,只有当组件所处的树中没有匹配到 Provider 时,其 defaultValue 参数才会生效
<CountContext value={count}> <Foo></Foo> <Bar></Bar> <Couter></Couter> </CountContext>
第二种使用方法:
useContext.js代码:
import { React, createContext } from 'react' var count = createContext(111) export default count;
app.js代码:
import React, { useEffect, useState, createContext } from 'react'; import Index from './components/Index' import List from './components/List' import count from './components/useContext' function App() { const [num, setNum] = useState(0) return ( <div> <button onClick={() => setNum(num + 1)}>点击</button> <count.Provider value={num}> <div>123123</div> <Index></Index> <List></List> </count.Provider> </div> ) }
index.js代码:
import React, { useContext } from 'react'; import count from './useContext' function Index() { const counts = useContext(count) return ( <div> <p>首页</p> <h3>数据共享{counts}</h3> </div> ) } export default Index;
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接