如何将初始状态作为我的高阶组件的道具传递?

Ema*_*him 4 javascript higher-order-functions composite-component reactjs recompose

我有一个Slider不处理自己状态的组件,相反,它包含在另一个SliderDrag管理状态的组件中,并将道具传递给Slider

我使用的是withState从recompose库实现这一目标.

这是我的Slider州初始状态

export const getInitialState = () => ({
  min: 0,
  max: 100,
  value: 50,
  step: 1,
  width: 100,
  dragging: false
});
Run Code Online (Sandbox Code Playgroud)

这是我的高阶组件 withState()

export const SliderDrag = withState('state', 'onChange', getInitialState())(
  ({state, onChange, action}) => (
  <Slider
  {...state}
  onDragStart={({x}) => {
    onChange(dragStart(x, state));
  }}
  onDrag={({x}) => {
    onChange(drag(x, state));
    action('value')(state.value);
  }}
  onDragEnd={() => {
    onChange(dragEnd(state));
  }}
 />
)
);
Run Code Online (Sandbox Code Playgroud)

这就是我想要使用的方式SliderDrag.我想传递道具来设置我的初始,state以便我可以Slider在我的应用程序中的不同上下文中使用此组件

export const interactive = (action) => (
  <Storypage theme={designerTheme}>
    <SliderDrag width={218} step={1} min={0} max={100} action={action}/>
  </Storypage>
);
Run Code Online (Sandbox Code Playgroud)

我是否需要使用compose从recompose库?任何建议或帮助将受到高度赞赏.:)

Ema*_*him 5

在一些帮助下,我能够解决我的问题.

我应该传递对设置initialState最后一个参数的函数的引用withState(),这样当initialState被调用时,我将有权访问props我传递给我的SliderDrag组件

这是我如何重构这个

const initialState = ({min, max, step, width, value}) => {
  debugger;
  return defaults({min, max, step, width, value}, defaultState());
};

export const SliderDrag = withState('state', 'onChange', initialState)(
  ({state, onChange, action}) => (
      <Slider
      {...state}
      ...
      />
  )
);
Run Code Online (Sandbox Code Playgroud)

defaults这里只是覆盖我传递的值,并给我一个新对象作为我的state.

这使我的component配置,因为任何其他的component可以用它和传承props作为initial state