【发布时间】:2019-05-29 06:45:22
【问题描述】:
在没有太多代码重复的情况下制作模态动态。我该怎么办?
我使用渲染道具将状态与布局分开。
interface State {
open: boolean;
}
interface InjectedModalProps {
onCloseModal: () => void;
onOpenModal: () => void;
open: boolean;
}
interface ModalProps {
children(props: InjectedModalProps): ReactNode;
}
class ModalProvider extends Component<ModalProps, State> {
state: State = {
open: false
};
onOpenModal = () => {
this.setState({ open: true });
};
onCloseModal = () => {
this.setState({ open: false });
};
render() {
const { open } = this.state;
const { children } = this.props;
return (
<Fragment>
{children({
onCloseModal: this.onCloseModal,
onOpenModal: this.onOpenModal,
open
})}
</Fragment>
);
}
}
const BathroomModal: FunctionComponent<Props> = ({ edit }) => (
<ModalProvider>
{({ onCloseModal, open, onOpenModal }) => {
return (
<Fragment>
<Modal open={open} center onClose={onCloseModal}>
<Container>
<h1>Badkamer toevoegen</h1>
{edit && <DeleteButton>Verwijderen</DeleteButton>}
<Divider />
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Est dolores incidunt ipsa,
earum nobis beatae facilis, dolore harum vitae nihil molestias repudiandae non quisquam
ab. Omnis unde atque voluptate ipsa!
</p>
<ContentBlock>
<h4>Type</h4>
<BathroomInputTypes />
<h4>Toilet</h4>
<Field name="toilet" options={[0, 1, 2, 3, 4, 5]} component={InputWithToggle} />
<h4>Douche</h4>
<Field name="shower" options={[0, 1, 2, 3, 4, 5]} component={InputWithToggle} />
<h4>Bad</h4>
<Field name="bath" options={[0, 1, 2, 3, 4, 5]} component={InputWithToggle} />
</ContentBlock>
<Divider />
<PrimaryButton onClick={onCloseModal} type="button">
{!edit ? 'Badkamer toevoegen' : 'Wijzigingen opslaan'}
</PrimaryButton>
</Container>
</Modal>
<SecondaryButton onClick={onOpenModal} type="button">
Badkamer toevoegen
</SecondaryButton>
</Fragment>
);
}}
</ModalProvider>
);
所以这就是我想出的。但是我认为通过将Modal组件提取到ModalProvider中可以更加重用。我也可以把触发按钮放在那里。但是,我也希望触发按钮是动态的,因此我可以使用图标而不是按钮来打开模式。
【问题讨论】:
标签: javascript reactjs typescript reusability