【发布时间】:2020-06-17 08:06:38
【问题描述】:
您好,我想以编程方式调用 reactstrap 模态对象,以便我可以重用它并根据情况调用它。目前,我通过使用 props buy 将模态状态作为道具传递,但我不想在父级上管理模态变量以确保我的代码更干净。让我解释一下我想做什么:
使用 reactstrap 中的基本模态示例,我正在删除按钮,因为当单击按钮并想要动态创建模态对象时,我不会调用它。 这就是我的想法......
/* Default simple reactstrap modal without button */
/* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React, { useState } from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
const ModalExample = (props) => {
const {
buttonLabel,
className
} = props;
const [modal, setModal] = useState(false);
const toggle = () => setModal(!modal);
const onModalLoad = () => { setModal(true); }
return (
<div>
<Modal isOpen={modal} toggle={toggle} className={className} onOpened={onlLoad}>
<ModalHeader toggle={toggle}>{props.title}</ModalHeader>
<ModalBody>
{props.body}
</ModalBody>
<ModalFooter>
<Button color="secondary" onClick={toggle}>OK</Button>
</ModalFooter>
</Modal>
</div>
);
}
export default ModalExample;
然后我想通过调用类似的东西来动态创建对象:
const parentComponent = () => {
const submitForm = event => {
if (condition1) {
React.createElement( ModalExample, {title: 'issue1', 'this is the problem'} );
}else if (condition2) {
React.createElement( ModalExample, {title: 'issue2', 'this is the problem'} );
}else if (condition3) {
React.createElement( ModalExample, {title: 'issue3', 'this is the problem'} ); }
}
}
return (
<span >
<Form onSubmit={submitForm}>
<Button color="primary" type="submit">
Submit
</Button>
</Form>
</span>
)
}
这有点类似于链接How to open/close react-bootstrap modal programmatically? 上讨论的内容,但这个选项没有被充分讨论,它对我不起作用。不知道我错过了什么。
【问题讨论】:
-
您是否能够控制它是否以编程方式显示在父级中?例如:` const parentComponent = () => { const [showModal, setShowModal] = useState(false) return ({showModal &&) }; `
} -
是的,但为了做到这一点,我在父组件中定义了可见性设置为 false 的组件,并跟踪标题、正文和可见性变量。然后我将可见性切换为真/假,因为我需要根据我想要显示的内容显示/隐藏和控制文本,但我觉得这不是一个干净的解决方案,因为我正在处理父模式的数据和变量组件。
-
如果您希望模态框在不同的场景中可重用,假设这可能意味着不同的标题或正文,那么您将不得不在某些时候将这些细节传递给它。即使在您动态创建元素的示例中......您需要在它被调用的地方定义元素,并且您需要传递一些东西。
-
我同意,这就是为什么我将道具传递为 {title: 'issue1', 'this is the problem'}, {title: 'issue2', 'this is the problem'},和 {title: 'issue3', 'this is the problem'} 将填写标题和正文...
标签: reactjs reactstrap