如何在react native中设置悬停样式



在reactjs中,我可以只使用包含.button. button:hover. button:active的样式表import styles from './styles.css',它就可以工作了。

在线转换器将此样式表转换为"button""button_hover""button_active"样式,但从react native中的样式表生成StyleSheet是不可行的。

如何在悬停和活动时更改元素样式?

.button {
background: #ff4931;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
transition: all 200ms ease;
}
.button:hover {
transition: all 100ms ease;
transform: scale(1.05);
box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
}
.button:active {
transition: all 50ms ease;
transform: scale(1.03);
background: #e5432d;
}

这就是我目前解决问题的方法,手动监听悬停启动和鼠标放下事件:

import React from 'react'
import { View } from 'react-native'
class EventView extends React.Component {
setStyles = (styles) => {
this.root.setNativeProps({
style: styles,
})
}
state = {
hover: false
}
render() {
const { activeStyle, hoverStyle, style, onPressIn, onPressOut, ...passThrough } = this.props
return (
<View
ref={(component) => { this.root = component }}
onMouseEnter={
() => {
this.setStyles(hoverStyle)
this.setState({ hover: true })
}
}
onMouseLeave={
() => {
this.setStyles(style)
this.setState({ hover: false })
}
}
onStartShouldSetResponder={() => true}
onResponderStart={
() => {
this.setStyles(activeStyle)
}
}
onResponderRelease={
() => {
this.setStyles(this.state.hover ? hoverStyle : style)
}
}
style={style}
{...passThrough}
/>
)
}
}
export default EventView

使用像这样的特殊视图

const styles = StyleSheet.create({
"button": {
"background": "#ff4931",
"boxShadow": "0 0 4px rgba(0, 0, 0, 0.3)",
"transition": "all 200ms ease"
},
"button_hover": {
"transition": "all 100ms ease",
"transform": "scale(1.05)",
"boxShadow": "0 0 8px rgba(0, 0, 0, 0.5)"
},
"button_active": {
"transition": "all 50ms ease",
"transform": "scale(1.03)",
"background": "#e5432d"
}
})
return (
<EventView
style={styles.button}
hoverStyle={[ styles.button_hover, styles.button ]}
activeStyle={[ styles.button_active, styles.button_hover, styles.button ]}
>

最新更新