如何将字符串和组件作为prop传递?

时间:2018-03-17 22:52:47

标签: javascript reactjs jsx

我可以传递这样的信息:

<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>}
`)} />

这是什么样的正确语法?

1 个答案:

答案 0 :(得分:2)

尝试将其作为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&gt; 16,则可能需要使用Fragments

import { Fragment } from 'react';

// ...

subtitle={
  <Fragment>
    This is a link: <Link to={this.props.post.author}>{this.props.post.author}</Link>
  </Fragment>
}
相关问题