【问题标题】:React: show object as working JS format?React:将对象显示为有效的 JS 格式?
【发布时间】:2017-03-03 15:02:18
【问题描述】:

我正在从事一个项目,我遇到了特定情况:

myjson:
{
    completeName: "my name is {this.state.myName+ " "+this.state.surname}"
}

component.js

var Component = React.createClass({ 
    getInitialState: function() {
        return({
            myName: "AKHA",
            surname: "HUND"
        })
    },
    render: function() {
        return (
            <div>{myData.completeName}</div>
        )
    }
})

但我得到的输出是:

my name is {this.state.myName+ " "+this.state.surname}

代替:

my name is AKHA HUND***

请帮帮我。

注意:使用 ES5。

谢谢

【问题讨论】:

    标签: javascript json object reactjs reactjs-flux


    【解决方案1】:

    您在.json 中存储的是字符串,而不是表达式,它不会以任何方式进行评估,您必须在 JS 代码中修改模板。

    使用 ES5 你可以做这样的事情:

    .json

    {
      completeName: "my name is %myName %surname"
    }
    

    component.js

    var Component= React.createClass({
        getInitialState: function(){
            return({
                myName: "AKHA",
                surname: "HUND"
            })
        },
        render: function(){
            const result = myData.completeName
                .replace("%myName", this.state.myName)
                .replace("%surname", this.state.surname);
    
            return (
                <div>{ result }</div>
            )
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2019-03-30
      • 1970-01-01
      • 2022-09-25
      • 2017-12-01
      • 2021-04-21
      相关资源
      最近更新 更多