Open monsterooo opened 6 years ago
withState可以为组件增加一个state和一个set state的函数,withState接收三个参数,第一个参数为state name,第二个参数是set state的函数名,第三个参数是一个初始值。
withState
state
set state
state name
set state函数有两种调用方式,具体类型如下:
stateUpdater<T>((prevValue: T) => T, ?callback: Function): void stateUpdater(newValue: any, ?callback: Function): void
withState( stateName: string, stateUpdaterName: string, initialState: any | (props: Object) => any ): HigherOrderComponent
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!')这样的匿名函数
withHandlers
() => setTitle('Hello,World!')
在codepen在线预览
withState 介绍
withState
可以为组件增加一个state
和一个set state
的函数,withState
接收三个参数,第一个参数为state name
,第二个参数是set state
的函数名,第三个参数是一个初始值。set state
函数有两种调用方式,具体类型如下:withState Flow Type
withState 实例
备注
withState
最好与withHandlers
一起使用,避免创建() => setTitle('Hello,World!')
这样的匿名函数在线DEMO
在codepen在线预览