如何根据行的当前激活key值修改行的背景颜色?
实现方案
你可以在渲染每行元素的时候,动态判断当前行的key对应的值是否和this.state.index相等,再给行元素绑定动态style或者class即可实现效果,具体实现逻辑如下:
- 渲染列表时遍历数据源,拿到每个子项的key值和
this.state.index做对比 - 对比为true时给对应行元素添加指定背景色的样式即可
代码示例
行内样式写法
假设你用div渲染行,参考写法:
{ 你的数据源.map((item, index) => { // 如果你用的key是数据源内的唯一字段,把index替换成对应字段即可 return ( <div key={index} style={{ backgroundColor: this.state.index === index ? 'black' : 'transparent', // 可搭配白色文字避免黑背景下内容看不见 color: this.state.index === index ? 'white' : 'inherit' }} > {/* 行内内容 */} {item.content} </div> ) }) }
Class样式写法
首先提前写好CSS样式:
.active-row { background-color: black; color: white; }
JSX部分调整为:
{ 你的数据源.map((item, index) => { return ( <div key={index} className={this.state.index === index ? 'active-row' : ''} > {/* 行内内容 */} {item.content} </div> ) }) }
适配第三方组件说明
如果你使用的是UI组件库的表格/列表组件,通常组件会提供行样式回调配置,比如antd Table组件的rowClassName属性,直接在回调函数内做上述判断返回对应类名即可实现同样效果。
内容的提问来源于stack exchange,提问作者heyooo12
相关产品推荐
相关产品推荐

