monsterooo / blog

and make promises by the hours
MIT License
14 stars 1 forks source link

recompose withState #15

Open monsterooo opened 6 years ago

monsterooo commented 6 years ago

withState 介绍

withState可以为组件增加一个state和一个set state的函数,withState接收三个参数,第一个参数为state name,第二个参数是set state的函数名,第三个参数是一个初始值。

set state函数有两种调用方式,具体类型如下:

stateUpdater<T>((prevValue: T) => T, ?callback: Function): void
stateUpdater(newValue: any, ?callback: Function): void

withState Flow Type

withState(
  stateName: string,
  stateUpdaterName: string,
  initialState: any | (props: Object) => any
): HigherOrderComponent

withState 实例

const { compose, withState } = Recompose;

const Foo = compose(
  withState('title', 'setTitle', "我是默认字符串!")
)(({ title, setTitle }) => (
  <div>
    <p>{title}</p>
    <button onClick={() => setTitle('Hello,World!')}>点击我更改标题</button>
    <button onClick={() => setTitle((prevValue) => `${prevValue},Hello,World!`)}>点击我也可以更改标题</button>
  </div>
))

备注

withState最好与withHandlers一起使用,避免创建() => setTitle('Hello,World!')这样的匿名函数

在线DEMO

codepen在线预览