在JSX中,如何将className设置为字符串+ {prop}


80

我对React有点陌生,并尝试将className设置为string + prop。但是我不确定该怎么做以及这是否是最佳实践。

所以我正在尝试做的,显然是行不通的,是这样的:

<a data-featherlight='string' + {this.props.data.imageUrl}>

我该如何写呢?

Answers:


188

您可以使用字符串串联

<a data-featherlight={'string' + this.props.data.imageUrl}>

或使用Template strings新的ES2015功能

<a data-featherlight={ `string${this.props.data.imageUrl}` }>

4

您也可以尝试:

<a data-featherlight={'string1' + this.props.data.imageUrl + 'string2'}>

要么

<a data-featherlight={ `string1 ${this.props.data.imageUrl} string2` }>

如果您使用的是Link组件,则可以这样进行串联:

<Link to={`getting-started/${this.props.message}`}>
     <h1>Under {this.props.message}/-</h1>
</Link>

1

据我所知,首先:

<a data-featherlight={'your string' + this.props.data.imageUrl}>

第二:

<a data-featherlight={`your string ${this.props.data.imageUrl}`}>

1
这与2016年接受的答案有何不同?
Arjan

0

在JSX中,对于className串联,您应该在大括号“ {}”之间放置字符串和道具,因为大括号表示JSX从JS角度评估内部内容。所以你应该尝试

<a data-featherlight={'string' + this.props.data.imageUrl}>

1
这与2016年接受的答案有何不同?
Arjan
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.