嗨!我是使用React的新手,甚至是使用钩子的新手,所以如果我的用法不正确,请更正我。实际上,我甚至在Google上为自己的问题而苦苦挣扎/想出这篇文章的标题-我该如何最好地将这个问题写成文字?
我有一个根组件,其中包含处于其状态的表,并且我正在使用Material UI
和react-csv
创建一个带有可保存表的保存按钮的NavBar。材质UI使用了钩子;我知道我的NavBar组件是否有状态,我可以编写data={this.props.table}
来获取表,但是我想知道在当前框架下如何下载表?有可能吗?
CodePen: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>
);
}
感谢任何建议/帮助!
答案 0 :(得分:1)
<NavBar table={this.state.table}/>
export default function PrimarySearchAppBar({table}) {
<CSVLink data={table}>
}