And*_*sko 51 html javascript node.js reactjs react-component
它背后有不同的原因,但我想知道如何简单地将自定义属性添加到JSX中的元素?
pet*_*mag 56
React 16本身支持自定义属性.这意味着向元素添加自定义属性现在就像将其添加到render
函数一样简单,如下所示:
render() {
return (
<div custom-attribute="some-value" />
);
}
Run Code Online (Sandbox Code Playgroud)
更多信息:
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的属性功能于反应-16.html
目前不支持自定义属性.有关详细信息,请参阅此未解决的问题:https: //github.com/facebook/react/issues/140
作为一种解决方法,您可以在componentDidMount
以下方面执行以下操作:
componentDidMount: function() {
var element = ReactDOM.findDOMNode(this.refs.test);
element.setAttribute('custom-attribute', 'some value');
}
Run Code Online (Sandbox Code Playgroud)
有关工作示例,请参阅https://jsfiddle.net/peterjmag/kysymow0/.(灵感来自syranide在本评论中提出的建议.)
Spa*_*hut 40
您可以使用ES6扩展运算符添加属性,例如
let myAttr = {'data-attr': 'value'}
Run Code Online (Sandbox Code Playgroud)
并在渲染方法中:
<MyComponent {...myAttr} />
Run Code Online (Sandbox Code Playgroud)
Luc*_*oli 18
考虑您要传递一个myAttr
以value 命名的自定义属性myValue
,这将起作用:
<MyComponent data-myAttr={myValue} />
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 es6,这应该可以工作:
<input {...{ "customattribute": "somevalue" }} />
Run Code Online (Sandbox Code Playgroud)
当我尝试将 SVG 与 React 结合使用时,我经常遇到这个问题。
我最终使用了一个相当肮脏的修复程序,但知道这个选项的存在很有用。vector-effect
下面我允许在 SVG 元素上使用该属性。
import SVGDOMPropertyConfig from 'react/lib/SVGDOMPropertyConfig.js';
import DOMProperty from 'react/lib/DOMProperty.js';
SVGDOMPropertyConfig.Properties.vectorEffect = DOMProperty.injection.MUST_USE_ATTRIBUTE;
SVGDOMPropertyConfig.DOMAttributeNames.vectorEffect = 'vector-effect';
Run Code Online (Sandbox Code Playgroud)
只要在开始使用 React 之前包含/导入它,它就应该可以工作。