【问题标题】:How to set a string as dynamic attributes in a JSX element如何在 JSX 元素中将字符串设置为动态属性
【发布时间】:2023-01-30 22:05:51
【问题描述】:

我想将一串文本添加到 JSX 元素的属性中。请看下面的示例,其中变量 otherAttributes 是一个字符串。实际上,在我的例子中,它是一个来自 CMS 的变量,我想将它添加为属性。

const otherAttributes = 'target="_blank" rel="follow"';
<a href={href || ''} class="inline-block px-4 py-2 rounded-full" {...otherAttributes}>{text}</a>

我得到输出为

<a 0="&quot;" 1="t" 2="a" 3="r" 4="g" 5="e" 6="t" 7="=" 8="\" 9="&quot;" 10="_" 11="b" 12="l" 13="a" 14="n" 15="k" 16="\" 17="&quot;" 18="&quot;" href="" class="inline-block px-4 py-2 rounded-full" >See more</a>

【问题讨论】:

  • 在传播之前将otherAttributes 转换为对象
  • 这就是为什么我问如何制作它。

标签: reactjs jsx


【解决方案1】:

这对我有用

import React from 'react';

export function App(props) {
  const otherAttributes = {
    target: '_blank',
    rel: 'follow'
  };
  const href = '';
  const text = "hello";
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
      <a href={href || ''} className="inline-block px-4 py-2 rounded-full" {...otherAttributes}>{text}</a>
    </div>
  );
}

// Log to console
console.log('Hello console')

【讨论】:

  • 你明确地制作了一个数组,这在我的情况下是不可能的,因为它是从 CMS 中获取的,用户可以在文本字段中设置任何内容。我可以期待任何 html 属性
猜你喜欢
  • 2018-07-17
  • 2021-11-08
  • 2011-09-11
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多