当我看到这个库时:
https://github.com/fkhadra/react-toastify
他们不使用redux。但是他们可以打电话给类似的东西
toast("Wow so easy !");
显示吐司成分。
无论如何,我有没有实现这一目标的关键?
答案 0 :(得分:1)
最简单的方法是将组件安装在另一个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>
);
}
}
在您的根应用程序中,您必须将此吐司安装到toastDiv
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);
上找到工作代码沙箱