这里是react的新手,我可以在下面请求你的帮助吗?
无法从其他功能组件中打开模式组件
我可以得到一个例子,其中一个组件有模式,从其他组件,我们可以在react js中使用react-modal包打开该模式,谢谢。
需要帮助
发布于 2021-03-03 12:15:44
在App.js中
import React from "react";
import Model from "./Model";
class App extends React.Component {
state = { status: false, text: "" };
handleClick = () => {
this.setState(prev => ({ status: !prev.status }));
};
handleChange = e => {
this.setState({ text: e.target.value });
};
render() {
const { status, text } = this.state;
return (
<>
<button onClick={this.handleClick}>Open photo entry dialog</button>
<ChildComponent
isOpen={status}
text={text}
handleChange={this.handleChange}
handleClick={this.handleClick}
/>
</>
);
}
}
const ChildComponent = ({ isOpen, text, handleChange, handleClick }) => {
return (
<>
{isOpen && (
<Model
status={isOpen}
handleClick={handleClick}
text={text}
handleChange={handleChange}
/>
)}
</>
);
};
export default App;在Model.js中
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Button, Modal, Form } from "react-bootstrap";
export default function Model({ handleClick, status, handleChange, text }) {
return (
<>
<Modal show={status} onHide={handleClick}>
<Modal.Header closeButton>
<Modal.Title>Gallary</Modal.Title>
</Modal.Header>
<Form.Group controlId="formBasicEmail">
<Form.Control
type="text"
value={text}
placeholder="Enter Something"
onChange={handleChange}
/>
</Form.Group>
<Modal.Body>
Woohoo, you're reading this text in a modal from your input:{" "}
<strong>{text}</strong>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClick}>
Close
</Button>
<Button variant="primary" onClick={handleClick}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}发布于 2021-03-03 12:19:19
这需要将函数作为props进行传递。我假设两个组件之间存在某种关系,因此您必须调用第一个组件中的第二个组件。
解决方案
让我们将包含Modal的组件调用为C1,将需要打开Modal的组件调用为C2。您需要将函数作为道具从C1传递到打开Modal的C2。
在C1中定义函数openModal:
openModal(){ \\Function to open the Modal
this.setState({modal:true}) \\modal state is used to define the state of the modal. When it is true, the modal is open.
}
将openModal函数从C1传递给C2,方法是在C1中使用以下代码:
<C2 openModal={this.openModal} />现在,在C2中,使用以下脚本打开Modal:
this.props.openModal() \\Use this in the event which opens the Modalhttps://stackoverflow.com/questions/66450601
复制相似问题