简体   繁体   English

在 html 中内联 css<a></a> 标记反应

[英]Inline css inside a html <a></a> tag in react

I have a link which I want to be black on default and white when I click on it.我有一个链接,当我点击它时,我想默认为黑色,白色。 Read about using the 'active' tag and setting color when it is active.阅读有关使用“活动”标签并在活动时设置颜色的信息。 Currently I have this code right here but it doesn't seem to change the color of the text when I press it.目前我在这里有这个代码,但是当我按下它时它似乎没有改变文本的颜色。

<a href={"#"} style={{textDecoration: 'none', color: 'black', active:{color: 'white'}}}>
   This is a link
</a>

All my search results showed how to use active in standard html, but I can't do that here since it's React.我所有的搜索结果都显示了如何在标准 html 中使用 active,但我不能在这里这样做,因为它是 React。 How am I supposed to achieve this?我应该如何实现这一目标?

Edit: I can't use a css files, my project will not compile them for reasons.编辑:我不能使用 css 文件,我的项目由于某些原因不会编译它们。

In CSS在 CSS 中

/* unvisited link */
a:link {
  color: red;
}

/* visited link */
a:visited {
  color: green;
}

/* mouse over link */
a:hover {
  color: hotpink;
}

/* selected link */
a:active {
  color: blue;
}

Customize accordingly.相应地进行定制。 Read more here在这里阅读更多

You cannot use pseudo classes like active, hover, visited directly in react in-line style.您不能在 React 内联样式中直接使用诸如 active、hover、visited 之类的伪类。 You can use many CSS-in-JSS libraries for that.为此,您可以使用许多 CSS-in-JSS 库。 For your case I think, this will be the CSS code :对于您的情况,我认为这将是 CSS 代码:

a{
color: black;
}
a:visited{
  color: white;
}

If you don't want to use CSS-in-JSS libraries, you can use onClick Event and mark the 'a' element with another style如果你不想使用 CSS-in-JSS 库,你可以使用 onClick 事件并用另一种样式标记 'a' 元素

//get the color from the local storage, if not there put `black` as default
const storedColor = localStorage.getItem("aColor") || JSON.stringify('black');
const [color,setColor] =useState(storedColor);
....
changeColor = e => {
setColor('white'); 
//Storing the color in local storage and use the color next time he opens the url again.
localStorage.setItem("aColor", JSON.stringify('white'));
}
....
<a onClick={changeColor} style={{color: color}}>
This is a link
</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM