reactjs - 如何在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.cart
或this.props.login
会做什么。我想创建一个功能,当我单击上面的两个图标时,我会被定向到另一个组件,但我不知道该怎么做。请帮助我理解它。
解决方案
Props
只是父组件发送给子组件的参数。在您的示例中this.props.cart
,并且this.props.login
是函数(我不确定cart
,但它被用作函数)。从您的示例中,当您单击图标时,您将调用父级发送的函数cart
。login
您的问题“您如何设置 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>
)
}
}
推荐阅读
- reactjs - 在运行时生成堆栈屏幕/堆栈屏幕名称时,如何键入检查 React Navigator 的堆栈导航路由?
- javascript - 带有 Laravel 的革命滑块
- react-redux - 如何在功能性 react-redux 组件中显示获取的数据?
- javascript - 如何使用“this”关键字传递函数
- sql - 连接日期的月份和年份以对其进行排序
- c++ - 如何检测 C/C++ 文件正在使用 Windows 特定的东西
- python-3.x - 在 tox.ini 中运行 flake8 时出现 InvocationError
- sql - SQL用另一个表的列中的值替换视图列中的所有行值
- python - 是否可以将数据加载到 plotly python 图中?
- facebook-graph-api - Graph API post_id/comments edge 权限错误