简体   繁体   English

我正在尝试在反应中实现 menuitem 但出现错误

[英]I am trying to implement menuitem in react but getting error

  • I am using MenuItem to implement dropdown menu in react.我正在使用 MenuItem 在 React 中实现下拉菜单。
  • I have imported the package also then too I am facing the error when running the server.我也导入了 package 然后我在运行服务器时也遇到了错误。
  • I tried looking for solution but not getting any exact method to solve the problem.我尝试寻找解决方案,但没有找到解决问题的确切方法。
  • Or is there any other way to implement the same?或者还有其他方法可以实现吗?
  • I want to have 2 options under drop down menu "User" and "Admin", so while registration the user will select his role.我想在下拉菜单“用户”和“管理员”下有 2 个选项,因此在注册时用户将 select 他的角色。
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { registerUser } from "../../actions/authActions";
import classnames from "classnames";
import MenuItem from '@material-ui/core/MenuItem';


class Register extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      email: "",
      password: "",
      password2: "",
      mobile: "",
      errors: {}
    };
  }

  componentDidMount() {
    // If logged in and user navigates to Register page, should redirect them to dashboard
    if (this.props.auth.isAuthenticated) {
      this.props.history.push("/dashboard");
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({
        errors: nextProps.errors
      });
    }
  }

  onChange = e => {
    this.setState({ [e.target.id]: e.target.value });
  };

  onSubmit = e => {
    e.preventDefault();

    const newUser = {
      name: this.state.name,
      email: this.state.email,
      password: this.state.password,
      password2: this.state.password2,
      mobile: this.state.mobile
    };

    this.props.registerUser(newUser, this.props.history);
  };

  render() {
    const { errors } = this.state;

    return (
      <div className="container">
        <div className="row">
          <div className="col s8 offset-s2">
            <div className="col s12" style={{ paddingLeft: "11.250px" }}>
              <h4>
                <b>Register</b>
              </h4>
              <p className="grey-text text-darken-1">
                Already have an account? <Link to="/">Log in</Link>
              </p>
            </div>
            <form noValidate onSubmit={this.onSubmit}>

              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.name}
                  error={errors.name}
                  id="name"
                  type="text"
                  className={classnames("", {
                    invalid: errors.name
                  })}
                />
                <label htmlFor="name">Name</label>
                <span className="red-text">{errors.name}</span>
              </div>

              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.email}
                  error={errors.email}
                  id="email"
                  type="email"
                  className={classnames("", {
                    invalid: errors.email
                  })}
                />
                <label htmlFor="email">Email</label>
                <span className="red-text">{errors.email}</span>
              </div>

              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.password}
                  error={errors.password}
                  id="password"
                  type="password"
                  className={classnames("", {
                    invalid: errors.password
                  })}
                />
                <label htmlFor="password">Password</label>
                <span className="red-text">{errors.password}</span>
              </div>

              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.password2}
                  error={errors.password2}
                  id="password2"
                  type="password"
                  className={classnames("", {
                    invalid: errors.password2
                  })}
                />
                <label htmlFor="password2">Confirm Password</label>
                <span className="red-text">{errors.password2}</span>
              </div>

              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.mobile}
                  error={errors.mobile}
                  id="mobile"
                  type="text"
                  className={classnames("", {
                    invalid: errors.mobile
                  })}
                />
                <label htmlFor="mobile">Mobile No.</label>
                <span className="red-text">{errors.mobile}</span>
              </div>

              <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
                Open Menu
              </Button>

              <Menu
              id="simple-menu"
              anchorEl={anchorEl}
              keepMounted
              open={Boolean(anchorEl)}
              onClose={handleClose}
              >
                <MenuItem onClick={handleClose}>Profile</MenuItem>
                <MenuItem onClick={handleClose}>My account</MenuItem>
                <MenuItem onClick={handleClose}>Logout</MenuItem>
              </Menu>


              <div className="col s12" style={{ paddingLeft: "11.250px" }}>
                <button
                  style={{
                    width: "150px",
                    borderRadius: "3px",
                    letterSpacing: "1.5px",
                    marginTop: "1rem"
                  }}
                  type="submit"
                  className="btn btn-large waves-effect waves-light hoverable blue accent-3"
                >
                  Create
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

Register.propTypes = {
  registerUser: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});

export default connect(
  mapStateToProps,
  { registerUser }
)(withRouter(Register));

The problem with below is handleClose and anchorEl property.下面的问题是 handleClose 和 anchorEl 属性。 I think you probably have copied it from material site.我认为您可能已经从材料站点复制了它。 And the example from where you copied is of f unctional component in react and you are using a class component.您复制的示例是反应中的功能组件,您正在使用class 组件。

Material site has demo with functional component.材料站点有功能组件的演示。 you can check source of code you copied https://material-ui.com/components/menus/你可以检查你复制的代码源https://material-ui.com/components/menus/

<Menu
          id="simple-menu"
          anchorEl={anchorEl}
          keepMounted
          open={Boolean(anchorEl)}
          onClose={handleClose}
          >
            <MenuItem onClick={handleClose}>Profile</MenuItem>
            <MenuItem onClick={handleClose}>My account</MenuItem>
            <MenuItem onClick={handleClose}>Logout</MenuItem>
          </Menu>

update it to class level anchorEl and handleClose it will work.将其更新为 class 级别的 anchorElhandleClose它将起作用。

demo link of functional menu of material site.素材站功能菜单演示链接。 check demo.js see anchorEL and handleclose and implement it in your logic https://codesandbox.io/s/sm1zv?file=/demo.js检查 demo.js 查看 anchorEL 和 handleclose 并在你的逻辑中实现它https://codesandbox.io/s/sm1zv?file=/demo.js

First, Button and Menu are not defined so import them:首先,未定义ButtonMenu ,因此导入它们:

import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';

Next, anchorEl , handleClick , handleClose are not defined接下来, anchorElhandleClickhandleClose未定义

  1. You can use a ref for anchorEl :您可以为anchorEl使用 ref :
class Register extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      email: "",
      password: "",
      password2: "",
      mobile: "",
      errors: {},
      open: false
    };
    this.menuRef = React.createRef();
  }

  ...
  1. Next, add handleClick and handleClose methods:接下来,添加handleClickhandleClose方法:
handleClose = () => {
  this.setState({
    open: false
  });
};

handleClick = () => {
  this.setState({
    open: true
  });
};

Also make sure to add state.open: false to the constructor.还要确保将state.open: false添加到构造函数中。

  1. Finally, change the Button and Menu markup to use the newly defined properties:最后,更改ButtonMenu标记以使用新定义的属性:
<Button
  aria-controls="simple-menu"
  aria-haspopup="true"
  onClick={this.handleClick}
>
  Open Menu
</Button>

<Menu
  id="simple-menu"
  ref={this.menuRef}
  anchorEl={this.menuRef}
  keepMounted
  open={this.state.open}
  onClose={this.handleClose}
>
  <MenuItem onClick={this.handleClose}>Profile</MenuItem>
  <MenuItem onClick={this.handleClose}>My account</MenuItem>
  <MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>

Here's a demo of the Menu opening and closing, with the react-router functionality taken out 下面是Menu打开和关闭的demo,去掉了react-router功能

暂无
暂无

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

相关问题 我正在尝试在反应中添加添加搜索过滤器,但我收到此错误 - I am trying to add add Search filter in react but I am getting this error 我正在尝试下载React js,但是又一次又一次出现此错误? - I am trying to download React js, but I am getting this error again and again? 我正在尝试实现一个对话流电子书以连接到 wordpress api,但出现错误:没有为平台定义响应:null - I am trying to implement a dialogflow webook to connect to wordpress api, but getting a Error: No responses defined for platform: null 为什么在尝试运行新的 React Native 项目时出现错误 - Why am I getting an error when trying to run a new react native project React Native:尝试从 Cloud Firestore 获取图像时出现错误 - React Native: I am getting error while trying to get image from cloud firestore 我正在尝试通过单击使用 React.js 的按钮来更改图像,但出现错误 - I am trying to change image by clicking buttons using React.js but getting error 即使我没有尝试渲染对象,获取对象也不能作为 React 子错误有效 - Getting a Objects are not valid as a React child error even though I am not trying to render an object 我正在尝试删除反应中的笔记,但我收到一个错误,您无法在初始化之前访问新笔记? - I am trying to delete a note in react but I am getting an error that you cannot access new notes before initialization? 我正在尝试使用 react-native 进行简单的路由,但我遇到了一些类似这样的错误 Failed building Javascript bundle - I am trying to do simple routing with react-native but I am getting some error like this Failed building Javascript bundle 为什么我收到未定义的错误错误? - Why am I a getting an error that react is undefined?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM