简体   繁体   中英

Non standard custom attributes in ReactJS?

This is regarding non-standard attributes. https://facebook.github.io/react/docs/tags-and-attributes.html

In react I have done this:

 React.createElement('div', {image:'blah', etc:'blah'});

I need image and etc to be set on the element with setAttribute , and I need react to use its smarts to maintain it as it changes.

A solution here https://stackoverflow.com/a/21654914/1828637 says to add it on componentDidMount but this is not a solution. The attribute will not be maintained as it changes by the react framework.

Is there anyway to tell react to set the attribute on my custom tags?

In react 16 custom attributes are now possible

// Your code:
<div mycustomattribute="something" />

// React 15 output:
<div /> 

// React 16 output:
<div mycustomattribute="something" />

react 16 custom attributes

This solution is to build on the linked answer by using the React lifecycle method componentWillReceiveProps to update the DOM element attributes with every change to props. For more information about all the lifecycle methods, see http://facebook.github.io/react/docs/component-specs.html .

(Since componentWillReceiveProps can be called more often than when the props actually change, you may wish to compare the props before actually setting them on the node.)

I've provide fiddle you can play with: https://jsfiddle.net/p4h267bo/ and the relevant part of the code is excerpted here:

var Hello = React.createClass({
  componentDidMount() {
    this.mirrorProps(this.props);
  },
  componentWillReceiveProps(nextProps) {
    this.mirrorProps(nextProps);
  },
  mirrorProps(props) {
    var node = ReactDOM.findDOMNode(this);
    node.setAttribute('name', props.name);
  },
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

Another alternative is to change the name of the attribute to something that react supports (such as the data-* attributes) :

render() {
    return (
      <div data-image='blah' data-etc='blah' />
    );
}

link to other supported attributes: https://facebook.github.io/react/docs/dom-elements.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM