React-router链接没有访问样式

时间:2015-12-20 13:53:33

标签: javascript html reactjs react-router

我有一个小网站,我正在使用React Router构建。我注意到只有主页链接才能获得访问过的样式。即使您访问它,另一个链接也不会获得访问样式。

https://jsfiddle.net/dfzkavbd/2/

使用Javascript:

if

HTML:

var dom = React.DOM;

var Router = React.createFactory(ReactRouter.Router);
var Link = React.createFactory(ReactRouter.Link);

var NavItem = React.createFactory(React.createClass({
    render: function() {
        var item = {
            marginLeft: "15px",
            marginRight: "15px",
            position: "relative",
            height: "100%",
            display: "flex",
            alignItems: "center"
        };
        return dom.div({ style: item }, this.props.children);
    }
}));

var NavBar = React.createFactory(React.createClass({
    render: function() {
        var navBarStyle = {
            backgroundColor: "black",
            height: "50px",
            display: "flex"
        };
        var innerNavBarStyle = {
            display: "flex",
            alignItems: "center",
            justifyContent: "initial",
            flexGrow: "1",
            color: "#777"
        };
        return dom.div({ style: navBarStyle },
            dom.div({ style: innerNavBarStyle }, 
                this.renderRightSide()
        ));
    },
    renderRightSide: function() {
        var rightStyle = {
            marginLeft: "auto",
            display: "flex",
            height: "100%"
        };
        return dom.div({ style: rightStyle }, 
            NavItem(null, Link({ to: "/Blog" }, "Blog")),
            NavItem(null, Link({ to: "/" }, "Home"))
        );
    }
}));

var Blog = React.createClass({
    render: function() {
        return dom.span(null, "Blog");
    }
});

var App = React.createClass({
    render: function() {
        return dom.div(null,
            NavBar(),
            this.props.children
        );
    }
});

var Home = React.createClass({
    render: function() {
        return dom.span(null, "Home");
    }
});

const routes = {
  component: App,
  childRoutes: [
    { path: 'Blog', component: Blog },
    { path: '/', component: Home }
  ]
};

ReactDOM.render(Router({ routes: routes }), document.getElementById("App"));

CSS:

<html class=""><head>
    <meta charset="UTF-8">
    <script src="https://fb.me/react-with-addons-0.14.3.js"></script>
    <script src="https://fb.me/react-dom-0.14.3.js"></script>
    <script src="https://npmcdn.com/react-router/umd/ReactRouter.min.js"></script>
</head>
<body style="margin: 0px;">
    <div id="App" class="app"></div>
</body></html>

如何将访问过的样式应用于所有访问过的链接?

1 个答案:

答案 0 :(得分:0)

我认为你可以使用classnames包并在onClick事件处理程序中将访问链接的类设置为true。但这并不会在重新加载时持续存在。如果您需要,则需要将设置保存到本地存储或其他内容。