【发布时间】:2022-06-15 04:35:48
【问题描述】:
我正在尝试以编程方式打开一个新窗口以展示信息。在新窗口中,我们可以根据下拉菜单的选择过滤掉信息,但 react-select 中的 select 不会在新窗口中加载样式(其他任何地方都可以使用下拉菜单)。
这是我正在使用的代码:
// app.tsx
import "./styles.css";
import React, { useState } from "react";
import Select from "react-select";
import WindowComponent from "./window";
import SelectComponent from "./form";
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
export default function App() {
const [show, setShow] = useState(false);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<a
onClick={() => {
setShow(!show);
}}
>
Click me
</a>
{show && (
<WindowComponent>
<SelectComponent />
</WindowComponent>
)}
<div style={{ marginTop: "50px" }}>Status: {show ? "True" : "False"}</div>
<div style={{ marginTop: "50px" }}>
<Select options={options} />
</div>
</div>
);
}
那么我们有form.tsx:
// form.tsx
import React from "react";
import Select from "react-select";
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
const SelectComponent = () => {
return <Select options={options} />;
};
export default SelectComponent;
最后但同样重要的是,我们如何生成新窗口:
// windows.tsx
import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
const WindowComponent = ({ children }) => {
/** ref to the new window opened */
const windowRef = useRef<Window>(null);
const [containerElement, setContainerElement] = useState<HTMLDivElement>(
null
);
useEffect(() => {
const newWindow = window.open("", "", "width=1200,height=400");
windowRef.current = newWindow;
const el = newWindow.document.createElement("div");
setContainerElement(el);
newWindow.document.body.appendChild(el);
newWindow.document.title = `Graph`;
return () => {
newWindow.close();
};
}, []);
return (
<div>
{containerElement && ReactDOM.createPortal(children, containerElement)}
</div>
);
};
export default WindowComponent;
我创建了一个codesandbox here。
如果您打开沙盒环境,您可以看到下拉菜单在 App 组件中正确呈现,但是当我们点击“点击我”时(不要忘记点击浏览器中的允许弹出窗口!)打开新窗口,该窗口内的下拉菜单没有样式。
关于发生了什么以及如何解决它的任何线索?我会很感激的。
【问题讨论】:
标签: javascript reactjs react-select