在React中串联变量和字符串

JavaScript

小胖LEY西门

2020-03-11

有没有办法整合React的花括号符号和href标签?假设我们在状态中具有以下值:

{this.state.id}

以及标签上的以下HTML属性:

href="#demo1"
id="demo1"

有没有一种方法可以将id状态添加到HTML属性中以获得类似这样的信息:

href={"#demo + {this.state.id}"}

这将产生:

#demo1

第748篇《在React中串联变量和字符串》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
JinJin小卤蛋 2020.03.11

exampleData =

        const json1 = [
            {id: 1, test: 1},
            {id: 2, test: 2},
            {id: 3, test: 3},
            {id: 4, test: 4},
            {id: 5, test: 5}
        ];

        const json2 = [
            {id: 3, test: 6},
            {id: 4, test: 7},
            {id: 5, test: 8},
            {id: 6, test: 9},
            {id: 7, test: 10}
        ];

example1 =


        const finalData1 = json1.concat(json2).reduce(function (index, obj) {
            index[obj.id] = Object.assign({}, obj, index[obj.id]);
            return index;
        }, []).filter(function (res, obj) {
            return obj;
        });

example2 =

        let hashData = new Map();

        json1.concat(json2).forEach(function (obj) {
            hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
        });

        const finalData2 = Array.from(hashData.values());

我推荐第二个例子,它更快。

Near卡卡西 2020.03.11

您几乎是正确的,只是放了一些引号。用正则引号将整个内容包装起来将按字面意义提供字符串#demo + {this.state.id}-您需要指出哪些是变量,哪些是字符串文字。由于里面的任何内容{}都是内联JSX 表达式,因此您可以执行以下操作:

href={"#demo" + this.state.id}

这将使用字符串文字#demo并将其连接到的值this.state.id然后可以将其应用于所有字符串。考虑一下:

var text = "world";

还有这个:

{"Hello " + text + " Andrew"}

这将产生:

Hello world Andrew 

您还可以将ES6字符串插值/ 模板文字与`(反引号)和${expr}(插值表达式)一起使用,这与您似乎想做的事情更接近:

href={`#demo${this.state.id}`}

这将基本上替代的值this.state.id,并将其连接到#demo等效于:"#demo" + this.state.id

斯丁 2020.03.11

连接道具/变量的最佳方法:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android