【问题标题】:How to pass string and component as prop?如何将字符串和组件作为道具传递?
【发布时间】:2018-08-26 19:37:45
【问题描述】:

我可以通过这样的好:

<CardTitle title={this.props.post.title} subtitle={
    <Link to={this.props.post.author}>{this.props.post.author}</Link>
} />

但我需要同时传递一个组件和一些字符串文本,但这样做不起作用:

<CardTitle title={this.props.post.title} subtitle={(`
    This is a link: ${<Link to={this.props.post.author}>{this.props.post.author}</Link>}
`)} />

什么是正确的语法?

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    尝试将它完全作为 React 元素传递,而不是作为字符串传递:

    <CardTitle
      title={this.props.post.title}
      subtitle={
        <span>
          This is a link: <Link to={this.props.post.author}>{this.props.post.author}</Link>
        </span>
      }
    />
    

    然后应该能够按原样呈现subtitle。如果你使用 React >16,你可能想使用 Fragments 来做这个:

    import { Fragment } from 'react';
    
    // ...
    
    subtitle={
      <Fragment>
        This is a link: <Link to={this.props.post.author}>{this.props.post.author}</Link>
      </Fragment>
    }
    

    【讨论】:

    • 有趣,我尝试了第一种方法,但它导致了错误,因为我没有包含容器标签(在你的情况下是跨度)。添加一个作品。谢谢。
    猜你喜欢
    • 2021-05-03
    • 2018-03-29
    • 2018-08-01
    • 2017-09-06
    • 2020-01-02
    • 2020-08-20
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多