Dynamically set attribute key (e.g. data-{foo}=“bar”) in React

試著忘記壹切 提交于 2020-01-14 10:16:29

问题


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


来源:https://stackoverflow.com/questions/37674813/dynamically-set-attribute-key-e-g-data-foo-bar-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!