在React中动态设置属性键(例如data- {foo} =" bar") [英] Dynamically set attribute key (e.g. data-{foo}="bar") in React

查看:358
本文介绍了在React中动态设置属性键(例如data- {foo} =" bar")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您知道密钥,在React中设置属性很简单,例如

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

有些库需要这种属性设置(例如 skrollr 等)

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

推荐答案

你可以使用一个对象来存储动态属性,然后使用JSX传播属性。

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

这是使用计算属性功能以及模板文字字符串。如果你没有使用ES6功能,你可以像这样执行ES5实现:

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

这篇关于在React中动态设置属性键(例如data- {foo} =&quot; bar&quot;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆