考虑一下我有一组组件,这些组件都有一些基本字段。一个示例可能是在错误状态下显示的弹出窗口。
这导致类似:
function MyComponent(props) {
const [showErr, setShowErr] = React.useState(false);
const [errMsg, setErrMsg] = React.useState('');
return <>
<...>
<SomePopup
open={showErr}
errMsg={errMsg}
/>
</>
}
虽然这很简单,但如果与其他组件之间没有更复杂的交互,则设置可能不会。这也是不必要的样板,并且违反了DRY。
状态当然可以在自定义钩子useError
中组合(或在这种简单情况下,在单个状态中)。但是,我也可以做到这一点,以便每当我声明一个对象具有useError
时,它也要设置组件吗?
这样,我可以防止出现类似“忘记弹出窗口”和“忘记设置useError状态”的错误-DRY错误。
代替钩子,考虑下面的高阶组件定义:
function withSomePopup(MyComponent) {
return function MyComponentWithSomePopup(props) {
const [showErr, setShowErr] = React.useState(false);
const [errMsg, setErrMsg] = React.useState('');
return <>
<MyComponent {...props} />
<SomePopup open={showErr} errMsg={errMsg} />
</>
};
}
然后您可以像这样包装您的组件:
export default withSomePopup(function MyComponent(props) {
return (
<...>
);
});