任何人都可以帮助我将此HOC转换为渲染道具

时间:2018-03-27 19:55:10

标签: reactjs redux

我见过博客说明所有HOC都可以转换为渲染道具。

我的代码中有这个HOC。我想知道这是否可以转换为渲染道具。

这是一个Connected HOC。

import React from 'react';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { modes } from '../../../modes';


const Wrapper = Component => (props) => {
  const { mode, ...rest } = props;
  if (mode === modes.VIEW) {
    return (<Component
      {...rest}
      disabled
    />);
  }

  return (<Component
    {...rest}
  />);
};

const mapStateToProps = state => ({
  mode: state.mode,
});

const composedHOC = compose(
  connect(mapStateToProps, null),
  Wrapper
);

export default composedHOC
;

1 个答案:

答案 0 :(得分:4)

如果你在谈论this pattern,那么我会说这是怎么做的。

打包机:

const WrapperBase = props =>
   props.mode === 'VIEW' ? 
      props.render({...props, disabled: true}) : 
      props.render({...props});

// using same mapStateToProps as in your HOC
const Wrapper = connect(mapStateToProps, null)(WrapperBase);
export default Wrapper;

用法:

<Wrapper render={({disabled}) => <div>disabled: {disabled ? 'true' : 'false'}</div>}/>

单元测试:

describe('Wrapper', () => {
  it('should pass the disabled prop to the inner component', () => {
    const options = {context: {}, childContextTypes: {}};
    const state = {mode: 'VIEW'};
    Wrapper = setStore(options, () => state)(Wrapper);
    const i = mount(<Wrapper render={({disabled}) => <div>disabled: {disabled ? 'true' : 'false'}</div>}/>, options);
    expect(i.html()).toBe('<div>disabled: true</div>');
  });
});

请注意,我使用了字符串VIEW,因为我没有您的modes.js文件。

相关问题