How to add custom html attributes in JSX

后端 未结 11 1818
南方客
南方客 2020-11-27 18:14

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

相关标签:
11条回答
  • 2020-11-27 18:39

    uniqueId is custom attribute.

    <a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>
    
    0 讨论(0)
  • 2020-11-27 18:42

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

    <MyComponent data-myAttr={myValue} />
    
    0 讨论(0)
  • 2020-11-27 18:45

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

    See my anwser here: Stackoverflow

    0 讨论(0)
  • 2020-11-27 18:45

    See attribute value in console on click event

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

    simple add customAttribute as your wish in render method

    render(){
        return <div>
    //..
        <button customAttribute="My Custom Event Message" onClick={this.alertMessage.bind(this) } >Click Me</button>
                </div>
            }
    //...
    
    0 讨论(0)
  • 2020-11-27 18:48

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

    componentDidMount(){
        const buttonElement = document.querySelector(".rsc-submit-button");
        const inputElement = document.querySelector(".rsc-input");
        buttonElement.setAttribute('aria-hidden', 'true');
        inputElement.setAttribute('aria-label', 'input');
      }
    
    0 讨论(0)
  • 2020-11-27 18:53

    I ran into this problem a lot when attempting to use SVG with 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-effect attribute on SVG elements.

    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.

    0 讨论(0)
提交回复
热议问题