首页 > 解决方案 > 如何在material-ui的导航栏中设置onClick?

问题描述

下面是为应用程序创建导航栏/标题的代码。我用过material-ui。

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import AccountCircle from "@material-ui/icons/AccountCircle";
import ShoppingCartOutlinedIcon from "@material-ui/icons/ShoppingCartOutlined";

const styles = (theme) => ({
  root: {
    width: "100%",
  },
  flex: {
    flex: 1,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
});

class Nav extends Component {
  render() {
    const { classes } = this.props;

    return (
      <AppBar position="static" elevation={0}>
        <Toolbar>
          <IconButton
            className={classes.menuButton}
            color="contrast"
            onClick={this.props.toggleDrawer}
          >
            <MenuIcon />
          </IconButton>
          <Typography className={classes.flex} type="title" color="inherit">
            Pizza Shop
          </Typography>
          <div>
            <IconButton color="contrast" onClick={this.props.cart}>
              <ShoppingCartOutlinedIcon />
            </IconButton>
            <IconButton color="contrast" onClick={this.props.login}>
              <AccountCircle />
            </IconButton>
          </div>
        </Toolbar>
      </AppBar>
    );
  }
}

Nav.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(Nav);

我是“道具”的新手,我不确定要做什么this.props.cartthis.props.login会做什么。我想创建一个功能,当我单击上面的两个图标时,我会被定向到另一个组件,但我不知道该怎么做。请帮助我理解它。

标签: reactjs

解决方案


Props只是父组件发送给子组件的参数。在您的示例中this.props.cart,并且this.props.login是函数(我不确定cart,但它被用作函数)。从您的示例中,当您单击图标时,您将调用父级发送的函数cartlogin

您的问题“您如何设置 onClick”的答案是您已经在login函数/方法上执行此操作。所以需要看父组件的实现。

下面我写了一个更具可读性的示例,请随意查看

import React from 'react'

class ChildrenComponent extends React.Component {
  render() {
    // This is doing the same thing, just we call the function / method in little different way
    // return <div onClick={() => { this.props.onShoppingSubmit() }}>Aaa</div>
    return <div onClick={this.props.onShoppingSubmit}>Aaa</div>
  }
}

class ParentComponent extends React.Component {
  handleShoppingSubmit = () => {
    // Do what every that function needs to do
    console.log('Hi from parent')
  }

  render() {
    return (
      <div>
        <ChildrenComponent onShoppingSubmit={this.handleShoppingSubmit} />
      </div>
    )
  }
}

推荐阅读