Conditional styles, hover and ReactJS

问题: I have an anchor within a <div>, the anchor uses conditional styling for it's background and this seems make it so that the a:hover style gets discarded. Actually it...

问题:

I have an anchor within a <div>, the anchor uses conditional styling for it's background and this seems make it so that the a:hover style gets discarded. Actually it doesn't matter if I have conditional or just a fixed color, if I remove the background-style from component.js the hover-effect from style.css kicks in.

My question is how do I achieve the hover effect while still having a conditional background-color?

component.js:

<div>
  <a href="#"
     style={{
       background: (day === 2) && "#f1f1f1"
     }} />
</div>

style.css:

div a {
  display: block;
}
div a:hover {
  background: blue;
}

回答1:

One solution would be to use !important to force the :hover behaviour even when inline styles as you have are applied, like so:

div a:hover {
  background: blue !important;
}

If dynamic inline styling is not required (ie you don't need a dynamic background color), then you'll typically want to avoid the use of !important in favour of class based styling:

JSX

<div>
  <a href="#" className={ (day === 2) && "dayTwoClass" } />
</div>

CSS

div a {
  display: block;
}

// Increased specificity of div to a causes blue background on hover
div a:hover {
  background: blue;
}

// Lesser specificity causes f1f1f1 background when not hovered
.dayTwoClass {
  background: #f1f1f1;
}

回答2:

This is a great use case for CSS stylesheet vs inline styles which will override due to css specificity.

Pop a class on it and do something like.

.conditional {
  background-color: #f1f1f1;
}

.conditional:hover {
  background-color: red;
} 

回答3:

Just to add, take a look at styled components https://www.styled-components.com/ . Its a matter of preference but using the style object can be a bit limiting and difficult to read (IMHO), some would say styled components is hard to read - your choice There's lots more to styled components so definitely worth taking a look. your use case would be something like below (or you could have your styled component in a different module)

import React from 'react'
import styled from 'styled-components'

const Link = styled.a`
  display: block;

  & :hover {
    background: ${props => props.dayValue === 2 ? white : blue};
  }
`

render(){
  return (<div> <Link href='' dayValue={this.props.dayValue}/></div>)
}
  • 发表于 2018-12-27 11:15
  • 阅读 ( 255 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除