【发布时间】:2018-12-11 12:53:12
【问题描述】:
我的主页上有一个透明的导航栏。我想在所有其他页面上给它一个黑色背景。你会怎么做?
上下文:React,没有 Redux。
【问题讨论】:
-
你用的是什么路由系统?
-
React-router-dom。 navbar 是一个简单的组件,直接添加到 App.js 的渲染部分。
我的主页上有一个透明的导航栏。我想在所有其他页面上给它一个黑色背景。你会怎么做?
上下文:React,没有 Redux。
【问题讨论】:
只要检查路线如下:
import {withRouter} from 'react-router-dom';
...
const SomeComponent = withRouter(props => <MyComponent {...props}/>);
class MyComponent extends React.Component {
...
SomeMethod () {
const {pathname} = this.props.location;
...
}
...
}
【讨论】:
假设您正确使用 react-router-dom,您可以使用 withRouter HOC 包装您的 Navbar 组件,然后从 this.props.match.path 检索实际位置。
然后它取决于您使用的样式方法(CSS-in-JS、Styled-Components、Styled-JSX、CSS 模块等)。
例如,假设您使用 CSS-in-JS,在您的 render 函数中,您可以这样做:
render () {
const { match: { path, isExact } } = this.props
const backgroundStyle = path === '/' && isExact === true
? { backgroundColor: 'transparent' }
: { backgroundColor: 'black' }
const navbarStyles = {
...styles.navbarWrapper,
...backgroundStyle
}
return (
<div style={navbarStyles}>
{/* Actual NavBar content here */}
</div>
)
}
【讨论】: