monsterooo / blog

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

recompose withHandlers #11

Open monsterooo opened 6 years ago

monsterooo commented 6 years ago

withHandlers 介绍

withhandlers接收一个对象函数为其接下来的组件创建事件处理函数,每个事件处理函数都接收一个参数,这个参数就是组件的props

withHandlers Flow Type

withHandlers(
  handlerCreators: {
    [handlerName: string]: (props: Object) => Function
  } |
  handlerCreatorsFactory: (initialProps) => {
    [handlerName: string]: (props: Object) => Function
  }
): HigherOrderComponent

实际调用也就是两种形式

// 1
withHandlers({
   handleClick: props => event => {
      alert(props.title)
   }
})
// 2
withHandlers(() => {
    return {
      handleClick: props => event => {
         console.log('我被点击了', props);
      },
    };
  })

withHandlers 实例

const { compose, withHandlers } = Recompose;
const ButtonEnhance = compose(
  withHandlers({
    handleClick: props => event => {
      alert('我被点击了, ' + props.title)
    }
  })
)(({ handleClick }) => (
  <button onClick={handleClick}>点我~~</button>
))

在线DEMO

codepen在线预览