新手在此做出反应。
TLDR:我有一个名为createNotification
的辅助函数,当被调用时,它会使用render((将<ToastNotification />
组件插入到container
元素中。如果我使用createPortal((,则不会附加任何内容。如果使用渲染,则尽管有多个触发器,但组件仅添加一次。
有人能帮我弄清楚发生了什么事吗?
谢谢
helpers.js
import { ToastNotification } from "carbon-components-react";
import { render, createPortal } from "react-dom";
export const createNotification = () => {
const container = document.getElementById("notificationContainer");
console.log(container); //just to check function is running and has found container
return render(<ToastNotification />, container); //works but only once, not on multiple triggers
return createPortal(<ToastNotification />, container); //doesn't render anything in container
};
上面的函数是根据需要从其他组件调用的:
login.js
import { createNotification } from "../../helpers";
const Login = () => {
const validateLogin = async (event) => {
createNotification();
// validation logic
performLogin();
};
const performLogin = async () => {
//axios call here
};
// main component content
return (
<>
<!-- validateLogin() called on form submit -->
</>
);
};
export default Login;
app.js
//imports
function App() {
return (
<div>
<div className="App"></div>
</div>
);
}
export default App;
谢谢
通过在render()
中添加createPortal()
自己解决了这个问题。
如果有人能提供解释,我们将不胜感激。
export const createNotification = () => {
const container = document.getElementById("notificationContainer");
console.log(container);
return render(createPortal(<ToastNotification />, container), document.createElement("div"));
};
createNotification没有安装在应用程序中的组件虚拟Dom。。。当您使用render(createPortal(时,您只需创建sperated应用程序。
import { createNotification } from "../../helpers";
export const createNotification = () => {
const container = document.getElementById("notificationContainer");
console.log(container); //just to check function is running and has found container
return createPortal(<ToastNotification />, container); //doesn't render anything in container
};
const Login = () => {
const [validate, setValidate] = useState(false);
const validateLogin = async (event) => {
if('some logic')
return setValidte(true)
setVAlidte(false)
};
useEffect(() => {
if(!valite)
return;
//axios heare
}, [validate])
// main component content
return (
<>
{!validate && <CreateNotfication/>}
<!-- validateLogin() called on form submit -->
</>
);
};