gpt4 book ai didi

javascript - 如何从 React 中的方法返回 JSX?

转载 作者:行者123 更新时间:2023-11-28 12:11:54 25 4
gpt4 key购买 nike

我对 React 还很陌生,我正在尝试从方法返回 JSX,代码如下:

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>

如您所见,element 包含一个我希望渲染 getGreeting 的 div,因为 user == true,它应该返回 greeting,它调用方法formatName。但是它返回一个错误:

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.

我在这里做错了什么?

最佳答案

getGreeting 应该返回一个 JSX 而不是一个对象

试试这个:

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

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

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

关于javascript - 如何从 React 中的方法返回 JSX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60290836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com