Javascript 如何在 JSX 中添加自定义 html 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31273093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:27:30  来源:igfitidea点击:

How to add custom html attributes in JSX

javascripthtmlnode.jsreactjsreact-component

提问by Andrey Borisko

There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?

这背后有不同的原因,但我想知道如何简单地向 JSX 中的元素添加自定义属性?

回答by peterjmag

EDIT: Updated to reflect React 16

编辑:更新以反映 React 16

Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a renderfunction, like so:

React 16 原生支持自定义属性。这意味着向元素添加自定义属性现在就像将其添加到render函数一样简单,如下所示:

render() {
  return (
    <div custom-attribute="some-value" />
  );
}

For more:
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: //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



Previous answer (React 15 and earlier)

上一个答案(React 15 及更早版本)

Custom attributes are currently not supported. See this open issue for more info: https://github.com/facebook/react/issues/140

当前不支持自定义属性。有关更多信息,请参阅此未决问题:https: //github.com/facebook/react/issues/140

As a workaround, you can do something like this in componentDidMount:

作为一种解决方法,您可以在以下内容中执行以下操作componentDidMount

componentDidMount: function() {
  var element = ReactDOM.findDOMNode(this.refs.test);
  element.setAttribute('custom-attribute', 'some value');
}

See https://jsfiddle.net/peterjmag/kysymow0/for a working example. (Inspired by syranide's suggestion in this comment.)

有关工作示例,请参阅https://jsfiddle.net/peterjmag/kysymow0/。(灵感来自 syranide 在此评论中的建议。)

回答by Spadar Shut

You can add an attribute using ES6 spread operator, e.g.

您可以使用 ES6 扩展运算符添加属性,例如

let myAttr = {'data-attr': 'value'}

and in render method:

并在渲染方法中:

<MyComponent {...myAttr} />

回答by Luca Fagioli

Consider you want to pass a custom attribute named myAttrwith value myValue, this will work:

考虑到您想传递一个名为myAttrvalue的自定义属性myValue,这将起作用:

<MyComponent data-myAttr={myValue} />

回答by Christian Steinmann

You can use the "is" attribute to disable the React attribute whitelist for an element.

您可以使用“ is”属性来禁用元素的 React 属性白名单。

See my anwser here: Stackoverflow

在此处查看我的答案: Stackoverflow

回答by rbhalla

I ran into this problem a lot when attempting to use SVG with react.

在尝试将 SVG 与 react 一起使用时,我经常遇到这个问题。

I ended up using quite a dirty fix, but it's useful to know this option existed. Below I allow the use of the vector-effectattribute on SVG elements.

我最终使用了一个相当脏的修复程序,但知道此选项存在很有用。下面我允许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';

As long as this is included/imported before you start using react, it should work.

只要在您开始使用 react 之前包含/导入了它,它就应该可以工作。

回答by Squibly

if you are using es6 this should work:

如果您使用的是 es6,这应该可以工作:

<input {...{ "customattribute": "somevalue" }} />

回答by Dixon Minnick

Depending on what version of React you are using, you may need to use something like this. I know Facebook is thinking about deprecating string refs in the somewhat near future.

根据您使用的 React 版本,您可能需要使用这样的东西。我知道 Facebook 正在考虑在不久的将来弃用字符串引用。

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'));

Facebook's ref documentation

Facebook 的参考文档

回答by GMK Hussain

See attribute value in console on click event

在单击事件中查看控制台中的属性值

//...
   alertMessage (cEvent){
           console.log(cEvent.target.getAttribute('customEvent')); /*display attribute value */
        }
//...

simple add customAttributeas your wish in render method

简单地在渲染方法中添加customAttribute作为您的愿望

render(){
    return <div>
//..
    <button customAttribute="My Custom Event Message" onClick={this.alertMessage.bind(this) } >Click Me</button>
            </div>
        }
//...

回答by KARTHIKEYAN.A

You can do it in componentDidMount()lifecycle method in following way

您可以componentDidMount()通过以下方式在生命周期方法中进行

componentDidMount(){
    const buttonElement = document.querySelector(".rsc-submit-button");
    const inputElement = document.querySelector(".rsc-input");
    buttonElement.setAttribute('aria-hidden', 'true');
    inputElement.setAttribute('aria-label', 'input');
  }

回答by jedmao

Depending on what exactly is preventing you from doing this, there's another option that requires no changes to your current implementation. You should be able to augment Reactin your project with a .tsor .d.tsfile (not sure which) at project root. It would look something like this:

根据究竟是什么阻止您这样做,还有另一个选项不需要更改您当前的实现。您应该能够在项目根目录下使用或文件(不确定是哪个)来扩充项目中的React。它看起来像这样:.ts.d.ts

declare module 'react' {
    interface HTMLAttributes<T> extends React.DOMAttributes<T> {
        'custom-attribute'?: string; // or 'some-value' | 'another-value'
    }
}

Another possibility is the following:

另一种可能性如下:

declare namespace JSX {
    interface IntrinsicElements {
        [elemName: string]: any;
    }
}

See JSX | Type Checking

JSX | 类型检查

You might even have to wrap that in a declare global {. I haven't landed on a final solution yet.

您甚至可能需要将其包装在declare global {. 我还没有找到最终的解决方案。

See also: How do I add attributes to existing HTML elements in TypeScript/JSX?

另请参阅:如何向 TypeScript/JSX 中的现有 HTML 元素添加属性?