我正在用React制作一个静态的Web应用程序。它有更多页面,所以我正在使用react-router-dom,但是当我使用Link标记时,它不仅显示在我想要的页面上,而且还显示在页面上以进行重定向。 除此之外,一切都工作正常:它指向的页面呈现得很好,但是链接位于左下角。谁能查看我的代码并告诉我我在做什么错?
我只希望链接“待办事项”显示在这里:
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { Link } from 'react-router-dom'
import Todo from '../apps/todo/Todo'
class Projects extends Component {
render() {
return (
<Router>
<div>
<Route exact path="/todo" component={Todo} />
<Link style={projectsTodo} href="/todo">
To Do List
</Link>
</div>
</Router>
)
}
}
链接显示在这里:
import React, { Component } from 'react'
import Header from './layout/Header'
import Todos from './Todos'
import uuid from 'uuid'
class Todo extends Component {
state = {
todos: [
{
id: uuid.v4(),
title: 'Learn React',
completed: false,
},
{
id: uuid.v4(),
title: 'Find suitable web hosting service',
completed: false,
},
],
}
delTodo = id => {
this.setState({
todos: [...this.state.todos.filter(todo => todo.id !== id)],
})
}
render() {
return (
<div>
<Header />
<Todos todos={this.state.todos} delTodo={this.delTodo} />
</div>
)
}
}
export default Todo
答案 0 :(得分:0)
之所以发生这种情况,是因为您在渲染链接时没有指定任何路线(因此它在所有路线上都被渲染)。请参阅first example of React Router以获得更好的理解。
如果您不希望发生这种情况,请定义另一个组件Home
(例如),该组件将保留链接,并在路由器中添加另一个将呈现该组件的Route。
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { Link } from 'react-router-dom'
import Todo from '../apps/todo/Todo'
const Home = props => {
return (
<div>
<h2>Home</h2>
<Link style={projectsTodo} href="/todo">
To Do List
</Link>
</div>
)
}
class Projects extends Component {
render() {
return (
<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/todo" component={Todo} />
</div>
</Router>
)
}
}