How to pass string and component as prop?

独自空忆成欢 提交于 2020-01-21 16:36:13

问题


I can pass something like this fine:

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

But I need to pass both a component and some string text, but doing this doesn't work:

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

What's the right syntax for this?


回答1:


Try passing it as a React Element altogether, not as a string:

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

Then should be able to render subtitle as is. If you're using React >16, you might want to use Fragments for this:

import { Fragment } from 'react';

// ...

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


来源:https://stackoverflow.com/questions/49342717/how-to-pass-string-and-component-as-prop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!