在 React #中,此浏览器无法识别标签
The tag is unrecognized in this browser in React
当我们使用浏览器中不存在的标签或以小写字母开头的组件名称时,会出现 React 警告“该浏览器无法识别该标签”。
要解决警告,请仅使用有效的标签名称并将组件的首字母大写。
下面是错误如何发生的示例。
应用程序.js
const App = () => { // ⛔️ Warning: The tag <p1> is unrecognized in this browser. // If you meant to render a React component, start its name with an uppercase letter. return ( <div> <div> <p1>Hello world</p1> </div> </div> ); }; export default App;
上面代码示例中的问题是我们使用了p1
浏览器中不存在的标签。
We have to make sure to only use tags that are supported. You can view all of
the supported tags in this
HTML elements reference doc.
You check whether a specific tag exists by using CTRL + F
and looking for the
tag, e.g. <li>
.
Only use valid tag names #
To solve the error in this case, we’d have to use an existing tag name, e.g.
h1
or p
.
App.js
const App = () => { return ( <div> <div> <h1>Hello world</h1> </div> </div> ); }; export default App;
Start component names with an Uppercase letter #
Another cause of the warning is when we start a component name with a lowercase
letter.
App.js
const greet = () => { return <h2>Hello world</h2>; }; const App = () => { // ⛔️ Warning: The tag <greet> is unrecognized in this browser. // If you meant to render a React component, start its name with an uppercase letter. return ( <div> <div> <greet /> </div> </div> ); }; export default App;
The issue is that the name of the greet
component starts with a lowercase
letter.
所有组件名称必须以大写字母开头,因为这是 React 用来区分我们编写的组件和浏览器中存在的内置标签的约定。
应用程序.js
// 👇️ capitalize first letter const Greet = () => { return <h2>Hello world</h2>; }; const App = () => { return ( <div> <div> <Greet /> </div> </div> ); }; export default App;
一旦我们将组件名称的第一个字母大写,React 就不会假设我们尝试使用浏览器中不存在的标签并且知道我们正在使用自定义组件。