Reactjs 不使用redux的重新加载组件
当我看到这个图书馆: 他们不使用redux。但他们可以称之为Reactjs 不使用redux的重新加载组件,reactjs,state,Reactjs,State,当我看到这个图书馆: 他们不使用redux。但他们可以称之为 toast("Wow so easy !"); 以显示toast组件 因此,对于我来说,是否有任何方法或关键点可以实现这一点而无需重复使用。实现这一点的最简单方法是将组件安装到另一个div上。为此,在index.html中添加一个div,如下所示 <div id="toastDiv"></div> 在这里找到工作代码沙箱您希望实现什么?在更新字段时显示组件?是的,但在非反应组件文件中显示,与库使用的方式相
toast("Wow so easy !");
以显示toast组件
因此,对于我来说,是否有任何方法或关键点可以实现这一点而无需重复使用。实现这一点的最简单方法是将组件安装到另一个div上。为此,在
index.html
中添加一个div,如下所示
<div id="toastDiv"></div>
在这里找到工作代码沙箱您希望实现什么?在更新字段时显示组件?是的,但在非反应组件文件中显示,与库使用的方式相同。
import React from "react";
let message = ""; // global variable we change when the user calls our function
// this function will change the global variable, and reset it after 5 secs
export function showMessage(userMessage) {
message = userMessage;
console.log("calling ...");
setTimeout(() => {
message = "";
}, 5000);
}
// our component
export class Toast extends React.Component {
constructor() {
super();
this.state = {
show: false,
message
};
}
// we continuously check for change in our global variable after our component has mounted and then set our states accordingly
componentDidMount() {
setInterval(() => {
this.setState({
show: message !== "",
message
});
}, 10);
}
// in the render we check if our states tell us to show or not the toast, and render the toast accordingly
render() {
return (
<div>
{this.state.show && (
<div style={{ position: "fixed", right: 10, top: 10, opacity: 100, background: 'steelblue' }}>
{this.state.message}
</div>
)}
</div>
);
}
}
import React from "react";
import ReactDOM from "react-dom";
import { Toast, showMessage } from "./toast";
import "./styles.css";
class App extends React.Component {
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button
onClick={() => {
// -------------- we show our message from here ------
showMessage("message");
// -------------- we show our message from here ------
}}
>
Show message
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// this is where we are mounting our toast
const toastDivElement = document.getElementById("toastDiv");
ReactDOM.render(<Toast />, toastDivElement);