有沒有合併React的大括號符號和href
標記的方法?假設我們有狀態的以下值:在React中連接變量和字符串
{this.state.id}
,並在標籤下面的HTML屬性:
href="#demo1"
id="demo1"
有沒有一種方法可以讓我的id
狀態添加到HTML屬性得到的東西像這樣:
href={"#demo + {this.state.id}"}
這將產生:
#demo1
有沒有合併React的大括號符號和href
標記的方法?假設我們有狀態的以下值:在React中連接變量和字符串
{this.state.id}
,並在標籤下面的HTML屬性:
href="#demo1"
id="demo1"
有沒有一種方法可以讓我的id
狀態添加到HTML屬性得到的東西像這樣:
href={"#demo + {this.state.id}"}
這將產生:
#demo1
你幾乎是正確的,只是放錯了幾個引號。用正則引號將整個東西包裝起來將會給你字符串#demo + {this.state.id}
- 你需要指出哪些是變量,哪些是字符串文字。由於內部{}
什麼是直列JSX 表達,你可以這樣做:
href={"#demo" + this.state.id}
這將使用字符串字面#demo
,它串聯到this.state.id
值。這可以應用於所有字符串。試想一下:
var text = "world";
而且這樣的:
{"Hello " + text + " Andrew"}
這將產生:
Hello world Andrew
您還可以使用ES6串插/ template literals用`(反引號)和${expr}
(插值表達),這更接近你似乎試圖做的事情:
href={`#demo${this.state.id}`}
這將基本上替代this.state.id
的值,並將其連接到#demo
。這相當於在做:"#demo" + this.state.id
。
到Concat的道具/變量的最佳方式:
var sample = "test";
var result = `this is just a ${sample}`;
//this is just a test