You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件中如何在JS表达式嵌入变量访问state属性

React类组件中动态访问state属性的问题

这是我的React代码:

const colors = ["RED", "BLUE", "GREEN", "YELLOW"];

// in class component 

constructor(props) {
  super(props);

  // these are filled in somewhere else in the code, but not shown here
  this.state = {
    redFiles: [],
    blueFiles: [],
    greenFiles: [],
    yellowFiles: []
  }
}
//somewhere else in the code:

render() {
  return (
    <div>
      {colors.map( color => 
        {this.state._____Files.length}      // problem area: how do I put color.toLowerCase() variable within that blank 
      )}
    </div>
  )
}

在标注的“问题区域”中,我该如何将color.toLowerCase()变量填入空白处,以分别获取this.state.redFiles.length、this.state.blueFiles.length、this.state.greenFiles.length和this.state.yellowFiles.length?


解决方案

要动态访问state中的属性,需要使用JavaScript的方括号属性访问语法,通过拼接字符串生成目标属性名:

修改问题区域的代码为:

{this.state[`${color.toLowerCase()}Files`].length}

或者用普通字符串拼接的方式:

{this.state[color.toLowerCase() + 'Files'].length}

原理说明

JavaScript对象的属性访问有两种方式:

  1. 点语法(如this.state.redFiles):仅适用于属性名是固定字符串的场景
  2. 方括号语法(如this.state[propName]):支持动态生成属性名,这里我们将color转成小写后与Files拼接,得到对应的state属性名(比如redFiles),从而实现动态访问。

内容的提问来源于stack exchange,提问作者penguin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:07:09