首页 > 解决方案 > 从函数返回带有 html 的字符串以在 JSX 中使用

问题描述

我是 JSX/React 的新手,如果有人问过这个问题,请先向我道歉,请参考这个问题。尝试删除一些内联代码,我创建了一个函数,该函数返回要在模板/JSX 中显示的值,这工作正常,除非它需要返回一个字符串 + 一个元素(链接元素),该函数如下所示:

let displayText = () => {
   let supportLink = <Link component={RouterLink} to={`/customers/${customer.id}/support`}>support</Link>
       
  return `We are unable to do something. If you have further questions, please contact our ${supportLink}`
  };

在实践中,这看起来像

We are unable to do something. If you have further questions, please contact our [object, object]

如何在我的字符串中包含该元素并使其正确显示?

标签: javascriptreactjsreact-routerjsx

解决方案


您正在返回一个模板字符串,因此它supportLink被强制为字符串,因此显示[object, object]

您需要修改 return 语句以返回ReactElement如下所示:

let displayText = () => {
   let supportLink = <Link component={RouterLink} to={`/customers/${customer.id}/support`}>support</Link>
       
  return (<>
    We are unable to do something. If you have further questions, please contact our {supportLink}
  </>)
};

推荐阅读