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

react

//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;

  

以上是 react contextType,useContext,Provider参数简易传递 的全部内容, 来源链接: utcz.com/z/381364.html

回到顶部