React项目中能否在对象数组的模板字符串内插入JSX元素?
在React中向对象数组的描述字段插入JSX元素的解决方案
你尝试在React项目的portfolio.jsx数组对象的description模板字符串中插入<a>等JSX元素,但页面显示[object Object]或字符串化的元素,两种插入方式均无效。
问题原因
模板字符串会将插入的JSX对象强制转换为字符串,而JSX对象转字符串的结果就是[object Object],因此直接在模板字符串中插入JSX的方式行不通。
解决方案
方法1:将description改为字符串与JSX的混合数组
把description字段从模板字符串改成包含字符串和JSX元素的数组,React可以直接渲染数组中的混合内容。
修改portfolio.jsx:
const learnReactLink = ( <a href="https://scrimba.com/learn/learnreact" target="_blank" rel="noopener noreferrer"> Learn React for free </a> ) export default [ { title: "Tenzies Game", imgUrl: "images/projects/tenziesgamepreview.png", description: [ "This is the final Capstone Project for ", learnReactLink, " that taught me a lot about React, everything from props, state, making API calls, useEffects, React forms, and more!" ], stack: [reactLogo, sassLogo], link: "https://fredtenziesgame.netlify.app/", codeLink: "https://github.com/fred-gutierrez/tenzies-game", } ]
在ProjectsItem.jsx中直接渲染description:
<div className="project-description"> {description} </div>
方法2:将description设为返回JSX的函数(可选)
如果需要处理更复杂的逻辑,可以把description定义为一个函数,返回拼接好的JSX内容:
修改portfolio.jsx:
export default [ { title: "Tenzies Game", imgUrl: "images/projects/tenziesgamepreview.png", description: () => ( <> This is the final Capstone Project for{" "} <a href="https://scrimba.com/learn/learnreact" target="_blank" rel="noopener noreferrer"> Learn React for free </a> {" that taught me a lot about React, everything from props, state, making API calls, useEffects, React forms, and more!"} </> ), stack: [reactLogo, sassLogo], link: "https://fredtenziesgame.netlify.app/", codeLink: "https://github.com/fred-gutierrez/tenzies-game", } ]
在ProjectsItem.jsx中调用该函数渲染:
<div className="project-description"> {description()} </div>
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

