gpt4 book ai didi

javascript - Reactjs 动态类名与 React 路由器

转载 作者:行者123 更新时间:2023-11-28 18:51:28 26 4
gpt4 key购买 nike

我有一个导航,当路径匹配时,每个项目的类都会变为事件状态。
例如)
当路径为http://localhost/food
<li class="active">food</li>

What is the best clean way to achieve this with ES6 syntax, React, React Router?
I don't want to use Flux or Redux only because of this... if i need to, then i want to know how to do it with Redux (because flux is more complicating and has some issues)

app.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link } from 'react-router';

import Home from './components/Home';
import Projects from './components/Projects';
import Blog from './components/Blog';
import createBrowserHistory from 'history/lib/createBrowserHistory';

class App extends React.Component {
render() {
return (
<div>
<div className="header">
<nav className="navbar">
<div className="navbar-header">
<ul className="right">
<li>
<a href="projects">PROJECTS</a>
</li>
<li>
<a href="blog">BLOG</a>
</li>
<li>
<a href="/">YOOCHAN</a>
</li>
</ul>
</div>
</nav>
</div>
<div className="container">{this.props.children}</div>
</div>
);
}
}

let documentReady = () => {
ReactDOM.render(
<Router history={createBrowserHistory()}>
<Route component={App}>
<Route path="/" component={Home} />
<Route path="projects" component={Projects} />
<Route path="Blog" component={Blog} />
</Route>
</Router>, document.getElementById('app')
);
};

$(documentReady);

package.json

  "devDependencies": {
"babel-core": "^6.3.21",
"babel-eslint": "^5.0.0-beta6",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"eslint": "^1.10.3",
"eslint-config-airbnb": "^2.1.1",
"eslint-loader": "^1.1.1",
"eslint-plugin-react": "^3.12.0",
"history": "^1.17.0",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-router": "^1.0.3",
"webpack": "^1.12.9"
}

最佳答案

通过使用react-routerLink帮助器

<Link className="class" activeClassName="active" to="/path">Path</Link>

链接到文档 https://github.com/rackt/react-router/blob/latest/docs/API.md#link

关于javascript - Reactjs 动态类名与 React 路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463614/

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