Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

reactjs - Show MaterialUi snackbar by method

I want to show message in material.ui by only call method not ading component to parent component (like toastify.js). So, I wrote example like below. But I couldn't call showSnack() method. How can I achieve this?

Note: I don't want add component to demo js like < SnackbarHelper />. I only want show snackbar calling by function.

CODESANDBOX LINK

Demo.js

import React from "react";
import Button from "@material-ui/core/Button";
import SnackHelper from "./snackHelper";

export default function PositionedSnackbar() {
  function showMessage() {
    console.log("I want call snackHelper.showSnack");
    // snackHelper.showSnack();
  }

  return (
    <div>
      <Button variant="contained" onClick={() => showMessage()}>
        SHOW MESSAGE
      </Button>
    </div>
  );
}

snackbarHelper.js

import React from "react";
import Snackbar from "@material-ui/core/Snackbar";

export default function SnackHelper() {
  const [state, setState] = React.useState({
    open: false
  });

  const { vertical, horizontal, open } = state;

  const showSnack = (newState) => () => {
    setState({ open: true, ...newState });
  };

  const handleClose = () => {
    setState({ ...state, open: false });
  };

  return (
    <div>
      <Snackbar
        anchorOrigin={{ vertical, horizontal }}
        open={open}
        onClose={handleClose}
        message=""
        key={vertical + horizontal}
      />
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found solution in this article for same thing what I was looking. Only difference is, this is for confirmation dialog and written by typescript. But, it can be easily changed to toast message by javascript. https://dev.to/dmtrkovalenko/the-neatest-way-to-handle-alert-dialogs-in-react-1aoe

You can get working example code https://codesandbox.io/s/neat-dialogs-3h5ou?from-embed=&file=/src/ConfirmationService.tsx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...