使用钩子在无状态组件中获得子状态
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用钩子在无状态组件中获得子状态相关的知识,希望对你有一定的参考价值。
自述文件:
嗨!我是使用React的新手,甚至是使用钩子的新手,所以如果我的用法不正确,请更正我。实际上,我甚至在Google上为自己的问题努力奋斗/想出这篇文章的标题-我该如何最好地将这个问题写成文字?
问题:
我有一个处于其状态的包含表的根组件,并且我正在使用Material UI
和react-csv
创建带有可保存表的保存按钮的NavBar。材质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"));
NavBar:
[我试图尽可能简化代码!]
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>
);
感谢您的任何建议/帮助!
答案
<NavBar table=this.state.table/>
export default function PrimarySearchAppBar(table)
<CSVLink data=table>
以上是关于使用钩子在无状态组件中获得子状态的主要内容,如果未能解决你的问题,请参考以下文章
在无状态组件中类型检查 styled-components 道具