本文介绍了如何为高阶功能组件设置PropTypes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将airbnb配置用于eslint,并向我发出此警告:
I'm using airbnb configuration for eslint and it's giving me this warning:
[eslint] 'isLoading' is missing in props validation (react/prop-types)
是否可以为isLoading设置PropTypes?
Is there a way to set PropTypes for isLoading?
const withLoading = Component => ({ isLoading, ...rest }) =>
(isLoading ? <LoadingSpinner /> : <Component {...rest} />);
这是我的用法示例:
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')
);
我也将其发布到jsfiddle: http://jsfiddle.net/BernieLee/5kn2xa1j/36/
I've also posted it to jsfiddle: http://jsfiddle.net/BernieLee/5kn2xa1j/36/
推荐答案
这是您需要的:
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,
};
这篇关于如何为高阶功能组件设置PropTypes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!