javascript - 大写的 React Element 抛出 Element type is invalid - 为什么?

标签 javascript reactjs

我正在尝试使用 React 创建自定义标签,如下所示:

// imports

// react
import React from 'react';
import ReactDOM from 'react-dom';

// ========================================

// classes & functions

const Home = <Home></Home>;

// ========================================

// exports

ReactDOM.render(
  Home,
  document.getElementById('root')
);

<Home></Home>抛出错误Element type is invalid .

将其更改为 <home></home将工作并将在浏览器中呈现此元素,但我得到此标志:

index.js:2178 Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

我猜这与定义 Home 有关。作为变量而不是函数或类?我在这里做错了什么?如何获取元素 <Home></Home>在浏览器中没有错误?

最佳答案

const Home = <Home></Home>;

您正在尝试渲染尚未定义的 Home 组件。

第二件事是您尝试重新分配应该提前声明的 Home

JSX (React) 将 upper-first 标签视为对范围内先前定义的变量/类的引用。

有效的用例可以是:

const Home = () => <div>hello world</div>;

const AnotherComponent = () => <Home></Home>;

关于javascript - 大写的 React Element 抛出 Element type is invalid - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51714046/

相关文章:

javascript - 引用本地文件而不是远程文件

javascript - 将 JSON 转换为数组 Javascript

reactjs - 更漂亮的冲突? (问号和点)在 typescript-react 中的 prop-bracket 中出现语法错误

javascript - 在 map 函数中 react onClick 处理程序

javascript - 将 Vue.js 混合到现有的 SSR 网站中?

javascript - "current value"独立于订阅者的概念

javascript - D3 js 从包含特定键值的对象中获取一个 d3.max

javascript - react : How to iterate through state and output to jsfiddle page

reactjs - 我什么时候应该使用 React.cloneElement 和 this.props.children?

reactjs - 如何使用react和Tailwind css制作svg图像作为背景图像?