无法使React router dom工作,“ InvalidCharacterError”

时间:2019-09-20 11:05:29

标签: reactjs react-router

在过去的两个小时里,我一直在梳头,试图使这段简单的代码起作用。

无论我给Route组件提供什么,它都会给我InvalidCharacterError失败,无法在“文档”上执行“ createElement”。

删除路线后,一切正常,组件Home自行工作。

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom'
import './App.css';

function App() {
  return (
    <Router>
      Hello !
      <Route path="/" exact component="{Home}" />
    </Router>
  );
}

const Home = () => (
  <div>
    <h1>This is the home.</h1>
  </div>
)

export default App;

这是错误:

InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('{Home}') is not a valid name.

1 个答案:

答案 0 :(得分:0)

您做错了,您将组件传递为错误的字符串,您需要将其作为组件传递。有关参考,请参阅react-router文档。

请参阅this沙箱以供参考

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom'
import './App.css';

function App() {
  return (
    <Router>
      Hello !
      <Route path="/" exact component={Home} />
    </Router>
  );
}

const Home = () => (
  <div>
    <h1>This is the home.</h1>
  </div>
)

export default App;