嗨,我想以编程方式调用reactstrap模态对象,以便我可以重用它并根据情况进行调用。目前,我通过使用props buy传递模式状态作为props来使其工作,但我不想不必在父级上管理modal变量以确保我的代码更简洁。让我解释一下我想做什么:
使用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 (
<div>
{showModal && <Modal title='my title text' body='my title body'}/>}
<button onClick={setShowModal(!showModal)}></button>
</div>
)
};
在您的示例中,您只是在更改标题,因此您可以将其存储在变量中……当然要在父级上存储:
const parentComponent = () => {
let title;
const submitForm = event => {
if (condition1) title = 'issue1';
else if (condition2) title = 'issue2';
else if (condition3) title = 'issue3';
}
return (
{showModal && <Modal title={title} body='my title body'}/>}
)
}
如果您绝对不想在父级上存储值,则可以在返回中使用完整的条件,但这对我来说似乎很麻烦(而且,实际上,这是父级的return语句,因此您无法将数据从父级中取出):
return (
<div>
{condition1 && <Modal title='issue1' body='my title body'}/>}
{condition2 && <Modal title='issue2' body='my title body'}/>}
{condition3 && <Modal title='issue3' body='my title body'}/>}
)
这假设只有一个条件可以成立-否则您可能会遇到三种模态!