How to add custom html attributes in JSX

后端 未结 11 1975
南方客
南方客 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:54

    EDIT: Updated to reflect 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 render function, like so:

    render() {
      return (
        
    ); }

    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


    Previous answer (React 15 and earlier)

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

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

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

提交回复
热议问题