简体   繁体   English

如何将 React 元素插入字符串

[英]How to insert React element into string

I would like to add React component into the string as JSX like this我想像这样将 React 组件作为 JSX 添加到字符串中

const name = <a href="#"> World </a>
const a = 'Hello, {name}'
return <div>{a}</div>

how can I get the following output我怎样才能得到以下 output

<div> Hello, <a href="#">World</a></div>

You don't need a string;您不需要字符串; instead, you also need to use JSX syntax (this won't work with a string):相反,您还需要使用 JSX 语法(这不适用于字符串):

const name = <a href="/">World</a>;
const a = <>Hello, {name}</>;
return <div>{a}</div>;

you can just use another function component to get the other HTML part, and then add it to the main app return function inside {} , here is a working snippet:您可以使用另一个 function 组件来获取另一个 HTML 部分,然后将其添加到主应用程序 return function 内{} ,这是一个工作片段:

 function name() { return (<a href="#"> World </a>); } const App = () => { const a = `Hello, ` return ( <div>{a} {name()}</div> ); }; ReactDOM.render( <App />, document.getElementById("react") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM