[英]How to apply different styles based on the browser location path name?
const activeStyle = {
border: '1px solid transparent',
borderColor: '#e4e6e8',
borderBottomColor: '#fff',
marginBottom: '-1px',
cursor: 'default'
}
const notActive = {
cursor: 'pointer'
}
class LoginSignup extends React.Component {
render() {
const pathName = this.props.history.location.pathname;
return (
<div style={{ pathName === '/login' ? ...activeStyle : ...notActive }}>
<Link to='/login'><span>Log in</span></Link>
</div>
<div style={{ pathName === '/signup' ? ...activeStyle : ...notActive }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>
</div>
);
}
}
export default withRouter(LoginSignup);
I want to apply different styles based on the location path name. 我想根据位置路径名应用不同的样式。 How to do that?
怎么做? I tried ternary operator inside style attribute but it shows Unexpted token, expected , error.
我在样式属性中尝试了三元运算符,但它显示了未标记,预期错误。
You will need to write it like so: 您将需要这样写:
<div style={pathName === '/login' ? activeStyle : notActive}>...</div>
If you need to concat some styles, I would do something along the lines: 如果您需要搭配一些样式,我会做一些大致的事情:
<div style={pathName === '/login' ? activeStyle : { ...activeStyle, ...notActive}}>...</div>
For readability, maybe rename the activeStyle
to defaultStyle
. 为了便于阅读,可以将
activeStyle
重命名为defaultStyle
。
you can try the code like below.
const pathName = this.props.history.location.pathname;
let headerlink='';
if(pathName=='/login'){
headerlink=<div style={{...activeStyle }}>
<Link to='/login'><span>Log in</span></Link>
</div>
}else{
headerlink=<div style={{...notActive }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>;
}
return headerlink;
Your spread operator is incorrect you need to spread it within object. 您的传播算子不正确,您需要在对象内传播它。 One of the following two approaches will work.
以下两种方法之一将起作用。
class LoginSignup extends React.Component {
render() {
const pathName = this.props.history.location.pathname;
return (
<div style={{ pathName === '/login' ? activeStyle : notActive }}>
<Link to='/login'><span>Log in</span></Link>
</div>
<div style={{ pathName === '/signup' ? activeStyle : notActive }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>
</div>
);
}
}
OR 要么
class LoginSignup extends React.Component {
render() {
const pathName = this.props.history.location.pathname;
return (
<div style={{ pathName === '/login' ? {...activeStyle} : {...notActive} }}>
<Link to='/login'><span>Log in</span></Link>
</div>
<div style={{ pathName === '/signup' ? {...activeStyle} : {...notActive} }}>
<Link to='/signup'><span>Sign up</span></Link>
</div>
</div>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.