简体   繁体   中英

How to concatenate React objects without JSX

How can I concatenate two React objects(React.createElement()) without JSX?

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.

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. you instead can pass them to createElement as an array of children elements

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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