我有一个正在构建的应用程序,它在左侧有一个导航栏,其中的图标在单击时会打开一个模式:
我已经成功地进行了设置,以便每当用户单击导航栏中的一个图标时都会加载不同的模式,我现在尝试更新状态以突出显示加载了哪个图标的模式,如下所示:
为了实现这一点,我开始掌握父/子关系和操纵状态。
父元素呈现一个<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>;
最后,我正在更新componentDidMount
,componentWillUnmount
以便它更新按钮样式(图标颜色和背景颜色):
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>
})
}
这主要按预期工作,但我正在努力完成一些事情:
- 这种当前方法适用于一个图标/模态组合,但难以扩展,因为我无法
componentDidMount
为每个图标/模态组合定义不同的功能 - 我目前的方法目前没有“取消选择”图标并将其恢复为原始样式
componentWillUnmount
- 我不知道如何包含
onClick
图标的属性:onClick={this.openModal("dashboard")}
。当我尝试将其包含在子元素中时,浏览器无法读取属性'openModal'
,因为它是父元素的一部分。
我不确定实现我所追求的最佳方法。