【问题标题】:How to set HTML data attributes inside render in React?如何在 React 的渲染中设置 HTML 数据属性?
【发布时间】:2019-10-23 13:07:16
【问题描述】:

我想在 React 中的 render() 中设置我的数据属性(特别是在使用 map() 时)。

这是我想要发生的事情:

let ownDataAttribute = 'data-foo'
...
render() {
    return (
    <>
    {
        array.map(item => <div [ownDataAttribute]="foobar" >{item.name}</div>
    }
    </>)
}

我想到的一个解决方案是:

let ownDataAttribute= "foo"

array.map(item => {
    let div = document.createElement('div')
    div.dataset[ownDataAttribute] = "foobar"

    // other code follows
})

但是,我发现这个解决方案太乏味了。是否有类似于显示的第一个 sn-p 的解决方案?

【问题讨论】:

    标签: html reactjs custom-data-attribute


    【解决方案1】:

    只需使用spread operator 将每个键值对作为道具传递。

    // your attributes
    const myAttributes = {
      ownDataAttribute: 'data-foo',
      otherAttributes: 'others'
    }
    
    array.map(item => (
      <div
        {...myAttributes} // all key-value pair are passed as prop
      >
        {item.name}
      </div>
    ))
    

    【讨论】:

      【解决方案2】:

      这应该可以完成,下面的代码使用Spread syntax

         array.map(item => {
         let attr[ownDataAttribute] = "foobar";
            return <div {...attr} >{item.name}</div>
         })
      

      【讨论】:

        猜你喜欢
        • 2017-09-03
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 2019-02-28
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        相关资源
        最近更新 更多