简体   繁体   English

根据变量值更改属性值

[英]Change prop value based on the value of a variable

I have json objects stored in separate files. 我有json对象存储在单独的文件中。 I want to pass one of the json objects as a prop into a display component, selecting the json to be passed in based on the value of a query param. 我想将一个json对象作为道具传递到显示组件中,根据查询参数的值选择要传递的json。

import React from 'react'
import _ from 'lodash'
import PageMain from '../Page'
import test1 from '../jsonData/test1'
import test2 from '../jsonData/test2'
import queryString from 'query-string'

class Page extends React.Component {
  componentWillMount() {
    const location = queryString.parse(location.search)
    // Assume BrandName = 'test1'
    let BrandName = _.get(location,'brand', '')
  }
  render(){
    return(
      <>
        <PageMain brand={BrandName}/>
      </>
    )
  }
}

export default Page

I want to pass in test1 (referencing the imported test1 file) but I am passing in 'test1' a string. 我想传递test1 (引用导入的test1文件),但我传递的是'test1'一个字符串。

I can't just use a ternary operator or similar because I will have a lot more jsonData. 我不能只使用三元运算符或类似的运算符,因为我将拥有更多的jsonData。

What you want is convert a string to module name in js. 您想要的是将字符串转换为js中的模块名称。

if it was variable, you could use: window["variableName"] or eval("variableName") 如果它是变量,则可以使用: window["variableName"]eval("variableName")

But in your example, they are modules. 但是在您的示例中,它们是模块。 you should first assign modules to variables or array. 您应该首先将模块分配给变量或数组。

import test1 from '../jsonData/test1' import test2 from '../jsonData/test2'; const tests = {'test1':test1, 'test2':test2};

Then use: <PageMain brand={tests[BrandName]}/> 然后使用: <PageMain brand={tests[BrandName]}/>


But i don't recommend this. 但是我不建议这样做。 you can just put your names in an array ['test1','test2'] and fetch json data with another way, not with import. 您可以将名称放入数组['test1','test2']并以其他方式(而不是导入)获取json数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM