如何将基于 React 状态的 JavaScript 变量插入到另一个变量中?

How is it possible to interpolate a JavaScript variable based on React state into another variable?

我有一个 React 组件,它从一个文件中提取图像、副本和应用程序所需的其他数据。我遇到的问题只是语法问题:如何根据组件的状态引用此数据?

data.js 看起来像这样(简化版):

import changingAgents from '../public/images/changing-agents.jpg';
import cta from '../public/images/cta.jpg';
import logo from '../public/images/logo.jpg';

export const images = {
  changingAgents,
  cta,
  logo,
}

export const copy = {
  services: {
    header: 'What are you looking for?',
    firstTimeInvestor: {
      title: 'First-Time Investor Service',
      intro: 'At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque.',
    },
    changingAgents: {
      title: 'Changing Agents',
      intro: 'At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti.',
    },
}

这里是组件的相关部分,Services.js:

import { copy, images } from '../../data';

export default class Services extends Component {
  state = {
    segmentTrigger: 'changingAgents',
  }

  changeSegmentTrigger(chosenSegmentTrigger) {
    this.setState({segmentTrigger: chosenSegmentTrigger})
  }

  render() {
    return (
      <div className="services">
        <h2>{copy.services.header}</h2>
        <Section backgroundImage={this.state.segmentTrigger} className="services__segment-triggers" >
          <div className="services__segment-triggers__select">
            <Button color="yellow" onClick={() => this.changeSegmentTrigger('firstTimeInvestor')} label="First-Time Investor" />
            <Button color="yellow" onClick={() => this.changeSegmentTrigger('changingAgents')} label="Changing Agents" />
          </div>
          <div className="services__segment-triggers__info">
            {/* Insert header here! */}
          </div>
        </Section>
      </div>
    )
  }
}

基本上我需要做的是在 <div className="services__segment-triggers__info"> 中添加将根据 this.state.segmentTrigger 发生变化的文本。我尝试了一些变体无济于事,例如:

这可能吗?前两个语法错误,第三个不起作用(这对我来说显然是合乎逻辑的,即使尝试它也有点冰雹玛丽,因为当然没有名为 [=21= 的键] 在 copy.services 对象中)。

您要找的答案是

<h2>{copy.services[this.state.segmentTrigger].title}</h2>

原因是您正在尝试访问 copy.services 的密钥,但是在用户开始单击按钮之前您不知道您正在尝试访问哪个密钥,以及您访问的是哪个密钥将动态决定。

对象和键在 JavaScript 中的工作方式是键在技术上是一个字符串,所以使用这个例子:

let x = {
  test1: 4,
  test2: 5,
  'test3': 6
};

x.test1 // is 4
x.test2 // is 5
x.test3 // is 6

x['test1'] // is 4
x['test2'] // is 5
x['test3'] // is 6

const y = 'test1';

x.y // undefined.  we never set a key of y.

x[y] // this is interpreted as x['test1'] so the result is 4