简体   繁体   中英

How to return JSX from a method in React?

I'm pretty new to React, I'm trying to return a JSX from a method, code as follows:

 import React, { useReducer } from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as serviceWorker from './serviceWorker'; const formatName = (user) => { return user.firstName + ' ' + user.lastName; } const getGreeting = (user) => { if (user) { return {greeting} } else { return {forbidden} } } const user = { firstName: 'John', lastName: 'Smith' }; const greeting = ( <h1>Hello {formatName(user)}</h1> ); const forbidden = ( <h1>Hello stranger!</h1> ); const element = ( <div>{getGreeting(user)}</div> ); ReactDOM.render( element, document.getElementById('root') );
 <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="root"></div>

As you can see, element contains a div which I wish to render getGreeting , since user == true , it should return greeting , which calls the method formatName . However it returns an error:

Error: Objects are not valid as a React child (found: object with keys {greeting}). If you meant to render a collection of children, use an array instead.

What am I doing wrong here?

更改return {greeting}return greeting没有括号的return greeting

getGreeting should return a JSX and not an object

try this:

const greeting = (
    <h1>Hello {formatName(user)}</h1>
);

const forbidden = (
    <h1>Hello stranger!</h1>
);

const getGreeting = (user) => {
    if (user) {
        return greeting
    }
    else {
        return forbidden
    }
}

In JavaScript, when you write:

return {greeting}

...what you are saying is "return an object, with a property named 'greeting', which is set to value of the variable greeting "

The last part of that, where the value is set, is an ES6 shortcut, essentially replacing { "greeting": greeting } with {greeting} for brevity's sake.

In other words, you are currently returning an object with a single property, "greeting", which is basically what your error message says. What you are returning is:

{
    "greeting": <h1>Hello ... </h1>
}

What you want to return is:

<h1>Hello ... </h1>

Since your greeting const is valid JSX, you can just return it directly! ie return greeting;

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