如何使用 response 动态设置 HTML5数据属性?

我想呈现一个 <select>输入的 HTML5属性,这样我就可以使用 jquery 图像选择器进行响应。我的代码是:

var Book = React.createClass({
render: function() {
return (
<option data-img-src="{this.props.imageUrl}" value="1">{this.props.title}</option>

问题是,即使 {this.props.imageUrl}作为 prop正确地传递,它也不是在 HTML 中呈现的——它只是作为 {this.props.imageUrl}呈现。如何使变量正确地传递到 HTML 中?

148336 次浏览

You should not wrap JavaScript expressions in quotes.

<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>

Take a look at the JavaScript Expressions docs for more info.

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {


props: {
'data-img-src': string
}

And when you refer to it later, you don't use the dot syntax

  render () {
return (
<option data-img-src={this.props['data-img-src']} >...</option>
)
}
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {


props: {
dataImgSrc: string
}

And when you refer to it later, you use the dot syntax

  render () {
return (
<option data-img-src={this.props.dataImgSrc} >...</option>
)
}
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.