如何在JSX中添加自定义html属性 [英] How to add custom html attributes in JSX
问题描述
背后有不同的原因,但我想知道如何简单地在JSX中为元素添加自定义属性?
There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?
推荐答案
编辑:更新以反映React 16
React 16本身支持自定义属性。这意味着向元素添加自定义属性现在就像将其添加到元素一样简单渲染
函数,如下所示:
render() {
return (
<div custom-attribute="some-value" />
);
}
更多信息:
https://reactjs.org/blog/2017 /09/26/react-v16.0.html#support-for-custom-dom-attributes
https://facebook.github.io/react/blog/2017/09/08/dom-attributes- in-react-16.html
目前不支持自定义属性。有关详细信息,请参阅此未解决的问题: https://github.com/facebook/react/issues/140
Custom attributes are currently not supported. See this open issue for more info: https://github.com/facebook/react/issues/140
作为解决方法,你可以在 componentDidMount
中执行类似的操作:
As a workaround, you can do something like this in componentDidMount
:
componentDidMount: function() {
var element = ReactDOM.findDOMNode(this.refs.test);
element.setAttribute('custom-attribute', 'some value');
}
参见 https://jsfiddle.net/peterjmag/kysymow0/ 是一个有效的例子。 (灵感来自syranide在此评论中的建议。)
See https://jsfiddle.net/peterjmag/kysymow0/ for a working example. (Inspired by syranide's suggestion in this comment.)
这篇关于如何在JSX中添加自定义html属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!