//useCallback import React, { Fragment, PureComponent, memo, useContext, createContext } from 'react'; // import About from './About'; const CountContext = createContext(); //创建context //类方式 class Foo extends PureComponent { static contextType = CountContext; //注入this.context,static 表示静态方法 render() { let count = this.context; return ( <div>{count}</div> ) } } //hooks方式 const Fbr = memo(() => { const count = useContext(CountContext); //CountContext是上文创建context对象 return ( <div> {count} </div> ) }); class App extends PureComponent { state = { count: 0, name: 0 } render() { return ( <Fragment> <CountContext.Provider value={this.state.count}> <Foo count={this.state.count} ></Foo> <Fbr></Fbr> </CountContext.Provider> //Provider传递参数 <button onClick={() => { this.setState(() => ({ count: this.state.count + 1 })) }}>加count</button> </Fragment> ) } } export default App;