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);
我想根据位置路径名应用不同的样式。怎么做?我在样式属性中尝试了三元运算符,但显示出未标记,预期错误。
答案 0 :(得分:2)
您将需要这样写:
<div style={pathName === '/login' ? activeStyle : notActive}>...</div>
如果您需要搭配一些样式,我会做一些事情:
<div style={pathName === '/login' ? activeStyle : { ...activeStyle, ...notActive}}>...</div>
出于可读性考虑,可以将activeStyle
重命名为defaultStyle
。
答案 1 :(得分:0)
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;
答案 2 :(得分:-1)
您的传播算子不正确,您需要在对象内传播它。以下两种方法之一将起作用。
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>
);
}
}