【发布时间】:2020-02-12 17:42:32
【问题描述】:
自述文件:
嗨!我是使用 React 的新手,甚至是使用钩子的新手,所以如果我的措辞不正确,请纠正我。事实上,我什至在谷歌上搜索我的问题/想出这篇文章的标题 - 我如何最好地用文字表达这个问题?
问题:
我有一个根组件,其中包含一个处于其状态的表格,我正在使用Material UI 和react-csv 创建一个带有可以保存表格的保存按钮的 NavBar。 Material UI 使用了钩子;我知道如果我的 NavBar 组件是有状态的,我可以写 data={this.props.table} 来获取表格,但我想知道在给定当前框架的情况下如何下载表格?有可能吗?
代码笔:https://codesandbox.io/embed/old-dust-88mrp
根组件:
import React from "react";
import ReactDOM from "react-dom";
import NavBar from "./NavBar";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
table: "this is a table"
};
}
render() {
return (
<div>
<NavBar />
<div>{this.state.table}</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
导航栏:
[我尽量简化代码!]
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import ListItemText from "@material-ui/core/ListItemText";
import SaveIcon from "@material-ui/icons/Save";
import Tooltip from "@material-ui/core/Tooltip";
import { CSVLink } from "react-csv";
const StyledMenu = withStyles({
paper: {
border: "1px solid #d3d4d5"
}
})(props => (
<Menu
elevation={0}
getContentAnchorEl={null}
anchorOrigin={{
vertical: "bottom",
horizontal: "center"
}}
transformOrigin={{
vertical: "top",
horizontal: "center"
}}
{...props}
/>
));
const StyledMenuItem = withStyles(theme => ({
root: {
"&:focus": {
backgroundColor: theme.palette.primary.main,
"& .MuiListItemIcon-root, & .MuiListItemText-primary": {
color: theme.palette.common.white
}
}
}
}))(MenuItem);
export default function PrimarySearchAppBar() {
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = event => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<AppBar position="static">
<Toolbar>
<div>
<Tooltip disableFocusListener title="Save">
<IconButton size="medium" onClick={handleClick} color="inherit">
<SaveIcon />
</IconButton>
</Tooltip>
<StyledMenu
id="customized-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<StyledMenuItem>
{/* In stateful components I could put this.props.table here,
but how does this translate to a stateless component? */}
<CSVLink data={"this is a test"}>
<ListItemText primary="Data" />
</CSVLink>
</StyledMenuItem>
</StyledMenu>
</div>
</Toolbar>
</AppBar>
</div>
);
}
感谢您的任何建议/帮助!
【问题讨论】:
标签: reactjs material-ui react-hooks