如何在渲染后用span标签包裹一个字符

Zot*_*tov 3 html javascript string reactjs

我有一个随机生成的字符串作为道具传递给子组件。它将它显示在段落标签中。示例字符串可以是:

猫、狗、鸟

鸟、鱼、仓鼠、鹅

猫、鱼、狗

ETC..

class Example extends React.Component {
  state = {
    string: ''
  };


  componentDidMount() {
    let newString = this.props.passedString.replace(',', '<span>,</span>');
    this.setState({string: newString});
  }

  render() {
    return (  
      <div><p>{this.state.string}</p></div>
    )
  };
}
Run Code Online (Sandbox Code Playgroud)

我想在子组件段落内的每个逗号周围添加标签。我尝试添加componentDidMount方法,用字符串中的 span 标签中包含的逗号替换每个逗号,但出于明显的原因,这只是将 span 标签添加为字符串的一部分,我不知道如何将它们显示为 html 中的实际标签或者如何修改已经呈现的段落。

Dac*_*nny 5

您可以使用String#splitArray#map方法来生成实现您所需要的 JSX:

/* Split the input randomString by `,` in to an array of string part */
const stringParts = randomString.split(',');

/* Use map to transform each string part to a React.Fragment. Prepend a
   comma enclosed by <span> for any string part that's not the first in
   the array */
const wrappedParts = stringParts.map((stringPart, index) => {

    return <React.Fragment>
    { index === 0 ? null : <span>,</span>}{stringPart}
    </React.Fragment> 
})
Run Code Online (Sandbox Code Playgroud)

这是一个功能组件,展示了这一点:

/* Split the input randomString by `,` in to an array of string part */
const stringParts = randomString.split(',');

/* Use map to transform each string part to a React.Fragment. Prepend a
   comma enclosed by <span> for any string part that's not the first in
   the array */
const wrappedParts = stringParts.map((stringPart, index) => {

    return <React.Fragment>
    { index === 0 ? null : <span>,</span>}{stringPart}
    </React.Fragment> 
})
Run Code Online (Sandbox Code Playgroud)
span {
background:lightgrey;
margin:0.1rem;
}
Run Code Online (Sandbox Code Playgroud)