【问题标题】:How to use react-toastr?如何使用反应烤面包机?
【发布时间】:2018-07-04 02:01:42
【问题描述】:

我正在尝试为 ReactJS 应用程序中的所有组件使用单个 ToastContainer,但我似乎不知道该怎么做。我试过了:

let container;

ReactDOM.render(
  <App container={container}>
    <ToasterContainer ref={ref => (container = ref)} />
  </App>,
  document.getElementById("root")
);

但是,我得到一个错误:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

有人有什么建议吗?

我愿意使用任何其他可以更好地与 React 应用配合使用的库。

我还应该提到,我的目标是能够显示来自仅包含辅助函数但本身不呈现任何内容的模块的 toast。到目前为止,我对react-toastr 的最大问题是它需要首先渲染ToasterContainer 组件才能显示任何祝酒词。我的理想解决方案是这样创建的:

let toastr = new Toastr(/* some options */);
toastr.show(message);

【问题讨论】:

  • 我可以给你推荐一个更好的插件react-toastify
  • 不也有同样的问题吗?需要先渲染一个组件?

标签: reactjs toastr


【解决方案1】:

我认为错误不在于烤面包机部分,

let container;
ReactDOM.render(<App container={container}>

在这里你已经创建并且没有初始化container 你已经将它分配给容器,因此容器的值未定义。

如果您尝试实现react-toastify,则不需要传递引用,只需在主组件中添加&lt;ToastContainer /&gt;

App = () =>(
  //add your routes here
  <ToasterContainer/>
)
ReactDOM.render(
  <App/>,
  document.getElementById("root")
);

【讨论】:

  • 那么您会推荐什么解决方案?
  • 我不知道你为什么在那里使用container={container}。如果不需要,请将其删除并尝试运行。
  • 因为我想将“容器”传递给我的其他组件,以便它们可以在需要时显示 toast,而我不知道该怎么做。
  • 容器的值是多少?
  • 好吧,我希望它成为对 ToastContainer 的引用,以便子组件可以使用它来发送消息。
猜你喜欢
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多