首页 > 解决方案 > 如何访问函数中的道具?

问题描述

我在从函数访问道具时遇到问题。

这是我的代码(包含所有这些的组件也是一个函数):

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)
};

标签: reactjs

解决方案


您可以从功能组件参数中解构 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>

}

推荐阅读