我尝试使用以下方法在其他.js文件中访问Modal的状态:
<Button
className="btn-round btn-white"
color="default"
outline
size="lg"
onClick={() => {
LogIn().setModal(true);
}}
>
Sign In
</Button
>
function LogIn() {
const [modal, setModal] = useState(false);
const [firstFocus, setFirstFocus] = useState(false);
const [lastFocus, setLastFocus] = useState(false);
return (
<>
<div>
<Modal
isOpen={modal}
>
<div className="modal-header justify-content-center">
<button
className="close"
type="button"
onClick={() => setModal(false)}
>
无效的挂钩调用。挂钩只能在功能组件的主体内部调用。可能由于以下原因之一而发生: 1.您的React和渲染器版本可能不匹配(例如React DOM) 2.您可能违反了《钩子规则》 3.您可能在同一应用中拥有多个React副本
答案 0 :(得分:0)
恢复状态。在功能组件状态下,组件处于局部状态。 React喜欢组成。 正在工作codeSandbox code供参考。
App.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Login from "./Login";
import { Button } from "reactstrap";
import "./styles.css";
function App() {
const [modal, setModal] = useState(false);
return (
<div className="App">
<Button
className="btn-round btn-white"
color="default"
outline
size="lg"
onClick={() => {
setModal(true);
}}
>
Sign In
</Button>
<Login modal={modal} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Login.js
import React from "react";
import { Modal, ModalHeader, ModalBody } from "reactstrap";
export default function Login({ modal }) {
return (
<Modal isOpen={modal}>
<ModalHeader>Modal title</ModalHeader>
<ModalBody>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</ModalBody>
</Modal>
);
}
希望有帮助!