javascript 选择前7个字符并添加颜色的字符串方法

xyhw6mcr  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(162)

我有反对意见:

const works = {
 0: ['item1', 'Step 1: first sentence here'],
 1: ['item2', 'Step 2: second sentence here'],
 2: ['item3', 'Step 3: third sentence here'],
}

我忽略了项目1、项目2、项目3,我只选择了第二个数组步骤1:....我正在使用Object.value()方法

const content = Object.values(works)
 const [value, setValue] = useState(0)
 console.log(content[value][1])

我想选择步骤1:(前7个字符)并添加类/颜色。可以吗?我正在使用此代码来选择前7个字符并将其与其他字符分开

{        <p className='w-50 con fs-5'>
            {
                 // I want to add class / color to first 7 characters, is it possible? 
            content[value][1].substring(0,7).toUpperCase() + 
            content[value][1].slice(7)
            }
         </p>
}
aor9mmx1

aor9mmx11#

用一个类引用将句子中需要自己颜色的部分 Package 在自己的范围内。要做到这一点,你需要将每个嵌套数组的第一个元素处的字符串分成子字符串,你可以用slice来完成。
在本例中,我使用了一个单独的Paragraph组件。

// Iterate over the array of nested arrays
// with `map` passing in each first element of the
// nested array as a text property to a paragraph component
function Example({ config }) {
  return (
    <section>
      {config.map(arr => <Para text={arr[1]} />)}
    </section>
  );
}

// Accept the text property
function Para({ text }) {

  // `slice` up the string into two parts
  const first = text.slice(0, 7).toUpperCase();
  const second = text.slice(7);

  // Build a paragraph using spans to indicate
  // which parts should be in colour
  return (
    <p>
      <span className="red">{first}</span>
      <span>{second}</span>          
    </p>
  );
}

const config = [
  ['item1', 'Step 1: first sentence here'],
  ['item2', 'Step 2: second sentence here'],
  ['item3', 'Step 3: third sentence here']
];

ReactDOM.render(
  <Example config={config} />,
  document.getElementById('react')
);
.red { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

相关问题