gpt4 book ai didi

reactjs - 如何设置高阶函数组件的 PropTypes?

转载 作者:行者123 更新时间:2023-12-03 13:18:43 27 4
gpt4 key购买 nike

我正在使用 eslint 的 Airbnb 配置,它给了我这个警告:

[eslint] Prop 验证中缺少“isLoading”(react/prop-types)

有没有办法为isLoading设置PropTypes?

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/

最佳答案

这是您需要的:

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,
};

关于reactjs - 如何设置高阶函数组件的 PropTypes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com