简体   繁体   English

以编程方式打开和关闭 React Material UI Snackbar 组件

[英]Open and close React Material UI Snackbar component programmatically

I'm trying to programme an SPA in React/Material-UI and I'm having some issues.我正在尝试在 React/Material-UI 中编写 SPA,但遇到了一些问题。 I've developed a modal login box that is launched from a button on a navbar.我开发了一个从导航栏上的按钮启动的模式登录框。 When the user presses submit I call a backend api using fetch and depending on the result of the returned status code I want to open a snackbar component with certain information or close the modal login window.当用户按下提交时,我使用 fetch 调用后端 api 并根据返回的状态代码的结果,我想打开带有某些信息的快餐栏组件或关闭模式登录 window。

I've learnt to open snackbars by clicking on a link but how can I open one programmically?我已经学会了通过单击链接来打开小吃店,但是如何以编程方式打开一个? I also need to close my modal window upon success of the api call and I don't know how to achieve this either.在 api 调用成功后,我还需要关闭我的模态 window ,我也不知道如何实现这一点。 I can also achieve this by manually clicking on a link that is bound to original button on the nav bar.我也可以通过手动单击绑定到导航栏上原始按钮的链接来实现这一点。

I've tried using the basic snackbar example from the docs and putting it in a separate component but it only shows how to launch those by clicking on a link that's already in the actual Snackbar functional component.我已经尝试使用文档中的基本小吃吧示例并将其放在一个单独的组件中,但它只显示了如何通过单击实际 Snackbar 功能组件中已经存在的链接来启动它们。 I need to know how to display a snackbar programmatically from another component.我需要知道如何从另一个组件以编程方式显示小吃吧。

I'm pretty sure I'm missing something obvious:)我很确定我错过了一些明显的东西:)

Login.js React Component Login.js 反应组件

import React, {Component} from 'react'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import CustomizedSnackbars from './CustomSnackbars'

class LoginDialog extends Component {

    constructor(props) {
        super(props);
        this.state = {username: "",
                      password: ""};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
      <some code>
    }

    handleSubmit(event) {
        event.preventDefault();
        const data = {
            "username":this.state.username,
            "password":this.state.password
        }

        fetch("https://mywebsite.com/auth/login", {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body:  JSON.stringify(data)
        })
        .then(function(response){
            if (response.status === 200) {
                console.log("good boye") 
                //---------------------------------
                // WANT TO CLOSE LOGIN DIALOG HERE;
                //---------------------------------
            } else if (response.status === 401) {
                console.log("naughty naughty")
                //---------------------------------
                // WANT TO DISPLAY SNACKBAR HERE
                //---------------------------------
            } else if (response.status === 502) {
                console.log("off it's hinges, innit")
            } else {
                console.log("sumat went bang")
            }
            return response.json();
        });
    }

    render() {
        return (
            <div className="modal-outer">
            <div className="modal-inner">
                <h3>Login</h3>
                <TextField
                />
                <br />
                <TextField
                />
                <Button variant="outlined" onClick={this.props.closePopup} color="secondary">
                    Cancel
                </Button>
                &nbsp;
                <Button variant="outlined" onClick={(event) => this.handleSubmit(event)} color="primary">
                    Login
                </Button>
            </div>
            </div>
        );
  }
}

export default LoginDialog

Can I call/make some kind of displaySnackbar method on the Snackbar component?我可以在 Snackbar 组件上调用/制作某种 displaySnackbar 方法吗? How can I call methods or functions on functional components?如何在功能组件上调用方法或函数?

I'm having real trouble understanding how React fits together.我很难理解 React 如何组合在一起。 I'm maninly a backend developer but I've used JQuery and other Javascript frameworks in the past.我主要是后端开发人员,但过去我使用过 JQuery 和其他 Javascript 框架。

Any help much appreciated!非常感谢任何帮助!

In React, you can only display things inside of render() .在 React 中,您只能在render()中显示内容。 This means that you need to include the snackbar component inside of your render.这意味着您需要在渲染中包含快餐栏组件。 You can use conditional rendering to decide whether to display them or not.您可以使用条件渲染来决定是否显示它们。 Usually this is done by some value in the component state.通常这是通过组件 state 中的某个值来完成的。 You should initialize a state flag to false in the constructor and then call setState() in your fetch response code to set it to true .您应该在构造函数中将 state 标志初始化为false ,然后在获取响应代码中调用setState()将其设置为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM