reactjs - 如何访问函数中的道具?
问题描述
我在从函数访问道具时遇到问题。
这是我的代码(包含所有这些的组件也是一个函数):
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
setAnchorEl(event.currentTarget);
}
function handleClose(val) {
setAnchorEl(null);
this.props.updateSelected(val)
}
return (
<div>
<IconButton onClick={handleClick}>
<FilterListIcon/>
</IconButton>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={() => {handleClose(1).bind(this)}}>Содержит текст</MenuItem>
<MenuItem onClick={() => {handleClose(2)}}>Не содержит текст</MenuItem>
<MenuItem onClick={() => {handleClose(3)}}>Начинается с</MenuItem>
<MenuItem onClick={() => {handleClose(4)}}>Заканчивается на</MenuItem>
</Menu>
</div>
如您所见,我已尝试绑定,但没有成功。
以下是我如何将此道具从另一个组件传递给组件:
<FilterOptions updateSelected={this.updateSelectedValue}/>
还有道具本身:
updateSelectedValue = async (val) => {
await this.setState({selectedValue: val});
console.log(this.state.selectedValue)
};
解决方案
您可以从功能组件参数中解构 prop。而且由于所有其他功能都在组件内定义,因此您可以从任何地方访问该道具。
我会给你的组件命名为 Test:
const Test = ({ updateSelected }) => {
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
setAnchorEl(event.currentTarget);
}
function handleClose(val) {
setAnchorEl(null);
updateSelected(val)
}
return (
<div>
<IconButton onClick={handleClick}>
<FilterListIcon/>
</IconButton>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={() => {handleClose(1).bind(this)}}>Содержит текст</MenuItem>
<MenuItem onClick={() => {handleClose(2)}}>Не содержит текст</MenuItem>
<MenuItem onClick={() => {handleClose(3)}}>Начинается с</MenuItem>
<MenuItem onClick={() => {handleClose(4)}}>Заканчивается на</MenuItem>
</Menu>
</div>
}
推荐阅读
- shopify - Shopify - 是否可以使用输入框更改产品的预览?
- javascript - 如何为位于数组内的值创建按钮,并且同一数组位于另一个数组内?
- python - 如何使用 python qrcode 库生成 QR 码到图像?
- sql - 取消旋转两个单独的列
- mysql - 拥有与节点一样多的 Pod
- flutter - 向 ClipPath 添加背景颜色不起作用
- assembly - RISC-V中保存哪些寄存器,哪些不保存
- mitmproxy - ios 13.7 上的问题
- laravel - 在子域上安装 Laravel 出现 Http 500 错误
- excel - 有没有办法复制带有锚单元格的 Excel 公式并让锚每 n 行更新一次?