首页 > 解决方案 > 使用变量获取道具内部的值

问题描述

有没有人尝试使用变量在道具中获取特定值?

通常,在道具中获取特定数据就像

const dataValue = props.table.data.rowData.account_number

但是在这种情况下,我需要道具的最后一部分是一个变量,因为account_number值不是固定的并且名称会有所不同。

那么有没有办法让我使用变量而不是在 prop 调用的过去部分添加固定名称?

像这样:

let theVariable = *somethingNew*;


const dataValue = props.table.data.rowData.theVariable

标签: reactjsreduxreact-reduxreact-props

解决方案


您可以通过属性括号访问来做到这一点:

let theVariable = somethingNew;

const dataValue = props.table.data.rowData[theVariable]

这也可以在对象创建期间使用:

const dataValue = {
   [theVariable]: {}
}

推荐阅读