React 中的内联 CSS 样式:如何实现 a:hover? [英] Inline CSS styles in React: how to implement a:hover?
问题描述
我非常喜欢 React 中的内联 CSS 模式并决定使用它.
I quite like the inline CSS pattern in React and decided to use it.
但是,您不能使用 :hover
和类似的选择器.那么在使用内联 CSS 样式时实现悬停高亮显示的最佳方法是什么?
However, you can't use the :hover
and similar selectors. So what's the best way to implement highlight-on-hover while using inline CSS styles?
#reactjs 的一个建议是拥有一个 Clickable
组件并像这样使用它:
One suggestion from #reactjs is to have a Clickable
component and use it like this:
<Clickable>
<Link />
</Clickable>
Clickable
具有 hovered
状态并将其作为道具传递给链接.但是,Clickable
(我实现它的方式)将 Link
包装在 div
中,以便它可以设置 onMouseEnter
和 onMouseLeave
到它.这让事情变得有点复杂(例如,span
包裹在 div
中的行为与 span
不同).
The Clickable
has a hovered
state and passes it as props to the Link. However, the Clickable
(the way I implemented it) wraps the Link
in a div
so that it can set onMouseEnter
and onMouseLeave
to it. This makes things a bit complicated though (e.g. span
wrapped in a div
behaves differently than span
).
有没有更简单的方法?
推荐答案
我遇到了同样的情况.非常喜欢在组件中保留样式的模式,但悬停状态似乎是最后一个障碍.
I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.
我所做的是编写一个 mixin,您可以将其添加到需要悬停状态的组件中.这个 mixin 将添加一个新的 hovered
属性到你的组件状态.如果用户将鼠标悬停在组件的主 DOM 节点上,它将设置为 true
,如果用户离开该元素,则将其设置回 false
.
What I did was writing a mixin that you can add to your component that needs hover states.
This mixin will add a new hovered
property to the state of your component. It will be set to true
if the user hovers over the main DOM node of the component and sets it back to false
if the users leaves the element.
现在在您的组件渲染函数中,您可以执行以下操作:
Now in your component render function you can do something like:
<button style={m(
this.styles.container,
this.state.hovered && this.styles.hover,
)}>{this.props.children}</button>
现在每次 hovered
状态改变时,组件都会重新渲染.
Now each time the state of the hovered
state changes the component will rerender.
我还为此创建了一个沙箱存储库,用于自己测试其中的一些模式.如果您想查看我的实现示例,请查看.
I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.
https://github.com/Sitebase/cssinjs/tree/feature-交互混合
这篇关于React 中的内联 CSS 样式:如何实现 a:hover?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!