如何将字符串和组件作为道具传递? [英] How to pass string and component as prop?

查看:49
本文介绍了如何将字符串和组件作为道具传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过这样的事情:

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

正确的语法是什么?

推荐答案

尝试将其作为React元素(而不是字符串)一起传递:

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

然后应该能够按原样呈现subtitle.如果您使用的是React> 16,则可能需要为此使用片段:

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>
}

这篇关于如何将字符串和组件作为道具传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆