简体   繁体   English

如何在没有 JSX 的情况下连接 React 对象

[英]How to concatenate React objects without JSX

How can I concatenate two React objects(React.createElement()) without JSX?如何在没有 JSX 的情况下连接两个 React 对象(React.createElement())?

Goal目标

My goal is to render message, the message should contain the user full name in bold.我的目标是呈现消息,消息应该包含粗体的用户全名。

Problem问题

The problem is that when I concatenate the react objects I am getting the message content and instead of the full name there is [object Object] in the string.问题是,当我连接反应对象时,我得到了消息内容,而不是全名,字符串中有[object Object]

Code代码

var firstName = React.createElement("b", {}, this.state.User["FirstName"])
var lastName = React.createElement("b", {}, this.state.User["LastName"])
var message = "Hello " + firstName + " " +  lastName
message += " You can edit your profile in the Users Table"
return React.createElement("p", {}, message)

You should concatenate them using array as follows:您应该使用数组连接它们,如下所示:

var firstName = React.createElement("b", {}, this.state.User["FirstName"])
var lastName = React.createElement("b", {}, this.state.User["LastName"])
var message = ["Hello ", firstName, " ", lastName]
message.push(" You can edit your profile in the Users Table")
return React.createElement("p", {}, message)

React.createElement returns you an Object of the component instance, you cannot directly concat it with a string. React.createElement返回给你一个组件实例的 Object,你不能直接用字符串连接它。 you instead can pass them to createElement as an array of children elements相反,您可以将它们作为子元素数组传递给 createElement

 var firstName = React.createElement("b", {},  this.state.User["FirstName"])
 var lastName = React.createElement("b", {}, this.state.User["LastName"])
 const message = ["Hello ", firstName, " ", lastName, " You can edit your profile in the Users Table"]
 return React.createElement("p", {}, message);

Working demo工作演示

 class App extends React.Component { render() { var firstName = React.createElement("b", {}, "Stack") var lastName = React.createElement("b", {}, "Overflow") return React.createElement("p", {}, ["Hello ", firstName, " ", lastName, " You can edit your profile in the Users Table"]); } } ReactDOM.render(<App/>, document.getElementById('app'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"/>

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

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