在对象或标签声明中传递道具时格式化文本

我正在传递这样的标签:(在React中)

<MainCard
    title="This is Title Text"
    subTitle="Hello World! This is Subtitle Text"
/>

在这里,我要制作“ Hello World!”强调就是用斜体显示。我该怎么写?

我努力了:

subTitle={<em> + "Hello Wolrd!" + </em> + "This is Subtitle Text"}

subTitle={"<em> Hello World! </em> This is Subtitle Text"}

但是它们都没有按预期工作。 您能告诉我如何实现吗?

评论
  • HeroA
    HeroA 回复

    在这里,您可以执行以下操作:

    subTitle={(<em>Hello World</em>)}
    
    // OR for multiple element
    
    subTitle={([<em>Hello World</em>, " Hi there" ])}
    
    const { useState , useEffect } = React;
    
    const Main = (props) => {
      return (
        <div>
          { props.title }
          <br/>
          { props.subTitle }
        </div>
      )
    }
    
    const App = () => {
    
      return (
        <div>
          <Main title="Vivek" subTitle={([<em>Hello World</em>, " Hi there" ])} />
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById('react-root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
    <div id="react-root"></div>
  • zvelit
    zvelit 回复

    您可以将文本包装在Fragment中,并将其作为反应节点向下传递,例如

    subTitle={
        <React.Fragment><em> Hello World! </em> This is Subtitle Text</React.Fragment>
    }
    

    工作片段

    const { useState , useEffect } = React;
    
    const MainCard = (props) => {
      return (
        <div>
          { props.title }
          <br/>
          { props.subTitle }
        </div>
      )
    }
    
    const App = () => {
    
      return (
        <div>
          <MainCard title="Vivek" subTitle={<React.Fragment><em>Hello World</em> Hi there</React.Fragment>} />
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById('app'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
    <div id="app"></div>