Dynamically set attribute key (e.g. data-{foo}=“ba

2019-06-25 01:21发布

问题:

Setting an attribute in React is straightforward if you know the key, e.g.

data-500={this.props.YDistance}

but how can one dynamically set part of the key. e.g.

data-{this.props.YDistance}="valueHere"

var Test = React.createClass({

    render: function() {
        return (
            <div data-{this.props.YDistance}="valueHere">
                {this.props.children}
            </div>
        );
    }

});

ReactDOM.render(
    <Test YDistance="500">Hello World!</Test>,
    document.getElementById('container')
);

There are libraries that require this kind of attribute setting (e.g. skrollr et al)

回答1:

You could use an object to store the dynamic properties and then use JSX spread attributes.

https://facebook.github.io/react/docs/jsx-spread.html

const propBag = { [`data-${foo}`] = 'bar' };
return (
  <div {...propBag}>
     {this.props.children}
  </div>
);

That is using the computed properties feature of ES6 as well as template literal strings. If you are not using ES6 features you could do an ES5 implementation like so:

var propBag = {};
propBag['data-' + foo] = 'bar';
return (
  <div {...propBag}>
     {this.props.children}
  </div>
);