How do I set PropTypes for Higher Order Functional Component?

只谈情不闲聊 提交于 2019-12-04 18:54:19

问题


I'm using airbnb configuration for eslint and it's giving me this warning:

[eslint] 'isLoading' is missing in props validation (react/prop-types)

Is there a way to set PropTypes for isLoading?

const withLoading = Component => ({ isLoading, ...rest }) =>
  (isLoading ? <LoadingSpinner /> : <Component {...rest} />);

Here's an example of how I use it:

const Button = ({ onClick, className, children }) => (
  <button onClick={onClick} className={className} type="button">
    {children}
  </button>
);
Button.propTypes = {
  onClick: PropTypes.func.isRequired,
  className: PropTypes.string,
  children: PropTypes.node.isRequired,
};
Button.defaultProps = {
  onClick: () => {},
  className: '',
  children: 'Click me',
};

const Loading = () => (
  <div>
    <p>Loading...</p>
  </div>
);

const withLoading = Component => ({ isLoading, ...rest }) =>
  (isLoading ? <Loading /> : <Component {...rest} />);

// How do I set propTypes for isLoading?
// I tried this but it didn't work:
// withLoading.propTypes = {
// isLoading: PropTypes.bool
// };

const ButtonWithLoading = withLoading(Button);

// The rendered component is based on this boolean.
// isLoading === false:  <Button /> is rendered
// isLoading === true:   <Loading /> is rendered
const isLoading = false;

ReactDOM.render(
  <ButtonWithLoading
      isLoading={isLoading} 
      onClick={() => alert('hi')}
  >Click Me</ButtonWithLoading>,
  document.getElementById('root')
);

I've also posted it to jsfiddle: http://jsfiddle.net/BernieLee/5kn2xa1j/36/


回答1:


Here is what you need:

const withLoading = (Component) => {
  const wrapped = ({ isLoading, ...rest }) => (
    isLoading ? <div>Loading</div> : <Component {...rest} />
  );
  wrapped.propTypes = {
    isLoading: PropTypes.bool.isRequired,
  };
  return wrapped;
};
withLoading.propTypes = {
  Component: PropTypes.element,
};



回答2:


Guessing isLoading is a boolean

withLoading.propTypes = {
    isLoading: React.PropTypes.bool
};


来源:https://stackoverflow.com/questions/46970806/how-do-i-set-proptypes-for-higher-order-functional-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!