有不同的原因,但我想知道如何在JSX中简单地向元素添加自定义属性?
有不同的原因,但我想知道如何在JSX中简单地向元素添加自定义属性?
在React 16中,本地支持自定义属性。这意味着将自定义属性添加到元素现在就像将它添加到render
函数一样简单:
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
作为一种解决方法,您可以在componentDidMount
中执行以下操作:
componentDidMount: function() {
var element = ReactDOM.findDOMNode(this.refs.test);
element.setAttribute('custom-attribute', 'some value');
}
请查看https://jsfiddle.net/peterjmag/kysymow0/,其中有一个可运行的示例。(灵感来自于syranide在此评论中的建议。)
您可以使用ES6展开运算符添加属性,例如:
let myAttr = {'data-attr': 'value'}
并在渲染方法中:
<MyComponent {...myAttr} />
data-
,否则无效的html属性和自定义属性现在将不起作用。 - DDMelement.setAttribute('custom-attribute', 'some value');
向DOM添加属性根本不是JSX。 - Spadar Shut如果你想传递一个名为myAttr
的自定义属性,值为myValue
,那么这将起作用:
<MyComponent data-myAttr={myValue} />
15.3.1
版本下测试过,因此您的反对意见并没有任何意义,因为您抱怨它无法与 15.5.4
版本兼容。其次,我刚刚使用了 ^15.6.1
进行了测试,它可以正常工作。请仔细检查您的代码。 - Luca Fagiolireact-dom
上而不是 react
。抱歉,是我的错 :)。 - GusDeCooLdata-
或aria-
来添加自定义属性。参见:https://facebook.github.io/react/docs/dom-elements.html - Scott如果您正在使用ES6,那么这应该可以工作:
<input {...{ "customattribute": "somevalue" }} />
vector-effect
属性的代码: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';
点击事件中在控制台查看属性值
//...
alertMessage (cEvent){
console.log(cEvent.target.getAttribute('customEvent')); /*display attribute value */
}
//...
在渲染方法中,您可以根据自己的需要添加 customAttribute 来定制属性。
render(){
return <div>
//..
<button customAttribute="My Custom Event Message" onClick={this.alertMessage.bind(this) } >Click Me</button>
</div>
}
//...
uniqueId是自定义属性。
<a {...{ "uniqueId": `${item.File.UniqueId}` }} href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>
var Hello = React.createClass({
componentDidMount: function() {
ReactDOM.findDOMNode(this.test).setAttribute('custom-attribute', 'some value');
},
render: function() {
return <div>
<span ref={(ref) => this.test = ref}>Element with a custom attribute</span>
</div>;
}
});
React.render(<Hello />, document.getElementById('container'));
根据阻止您执行此操作的具体原因,还有另一种选项,无需更改当前实现。您应该能够在项目中使用.ts
或.d.ts
文件(不确定哪个)来增强React。它看起来应该是这样的:
declare module 'react' {
interface HTMLAttributes<T> extends React.DOMAttributes<T> {
'custom-attribute'?: string; // or 'some-value' | 'another-value'
}
}
另一种可能性是以下内容:
declare namespace JSX {
interface IntrinsicElements {
[elemName: string]: any;
}
}
你甚至可能需要将其包装在declare global {
中。我还没有最终解决方案。
aria-modal=true
,你将更改(变为 false)存储在 aria/data 属性的 store 中,但是除此之外没有任何其他更改(例如组件的内容、类或其中的变量),因此 ReactJs 将不会更新该组件中的 aria/data 属性。我已经研究了整整一天才意识到这一点。 - Alexey Nikonov