react contextType,useContext,Provider参数简易传递

谁说我不能喝 提交于 2020-04-07 20:43:27
//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;

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!