0

我有一个正在构建的应用程序,它在左侧有一个导航栏,其中的图标在单击时会打开一个模式:

在此处输入图像描述

我已经成功地进行了设置,以便每当用户单击导航栏中的一个图标时都会加载不同的模式,我现在尝试更新状态以突出显示加载了哪个图标的模式,如下所示:

在此处输入图像描述

为了实现这一点,我开始掌握父/子关系和操纵状态。

父元素呈现一个<div>捕获状态的:

<div>
   <ActiveDashboardIcon data={this.state.data} />
</div>

然后我有一个填充父级的子函数<div>

const ActiveDashboardIcon = ({ data }) =>
    <div>
        {data ? data :
            <ListItem button id="dashboardIcon" style={{ backgroundColor: 'black' }}>
                <ListItemIcon>
                    <DashboardIcon style={{ color: 'white' }} />
                </ListItemIcon>
            </ListItem>
        }
    </div>;

最后,我正在更新componentDidMountcomponentWillUnmount以便它更新按钮样式(图标颜色和背景颜色):

componentDidMount() {
    this.setState({
        data:
            <ListItem button id="dashboardIcon" style={{ backgroundColor: 'white' }}>
                <ListItemIcon>
                    <DashboardIcon style={{ color: 'black' }} />
                </ListItemIcon>
            </ListItem>
    })
}

componentWillUnmount() {
    this.setState({
        data:
            <ListItem button id="dashboardIcon" style={{ backgroundColor: 'black' }}>
                <ListItemIcon>
                    <DashboardIcon style={{ color: 'white' }} />
                </ListItemIcon>
            </ListItem>
    })
}

这主要按预期工作,但我正在努力完成一些事情:

  1. 这种当前方法适用于一个图标/模态组合,但难以扩展,因为我无法componentDidMount为每个图标/模态组合定义不同的功能
  2. 我目前的方法目前没有“取消选择”图标并将其恢复为原始样式componentWillUnmount
  3. 我不知道如何包含onClick图标的属性: onClick={this.openModal("dashboard")}。当我尝试将其包含在子元素中时,浏览器无法读取属性'openModal',因为它是父元素的一部分。

我不确定实现我所追求的最佳方法。

4

0 回答 0