首页 > 解决方案 > React Native Web/Expo:如何在 Pressable 上模拟焦点可见?

问题描述

我正在尝试在 React Native Web 中的 Pressable 组件上手动重新创建焦点可见行为。这种人为行为是这样的,当您单击 Pressable 组件时,它将具有一组样式,但如果您使用键盘上的选项卡聚焦它,它将具有一组不同的样式。

值得庆幸的是,react-native-web 上的 Pressable 内置了按下、悬停和聚焦的变体。但问题是,每当按下 Pressable 时,此后的焦点仍然是正确的。

  1. 有没有办法让被按下后的专注不真实?
  2. 或者,是否有其他技巧可以人为地重新创建焦点可见行为?
<Pressable 
  style={({pressed, hovered, focused}) => [
      {
        backgroundColor: pressed ? "orange" : hovered ? "green" : focused ? "red" : "lightgray", 
        padding: 20 
      }
]}>
    {
      ({pressed, hovered, focused}) => (
        <Text>
          {pressed ? "Pressed" : hovered ? "Hovered" : focused ? "Focused" : "Default"}
        </Text>
      )
    }
</Pressable>

这里是世博小吃。不知道为什么悬停在这种小吃上不起作用,但点击后,它会保持红色(聚焦)。点击后有什么办法让它变回灰色?

标签: reactjsreact-nativeexpofocusreact-native-web

解决方案


弄清楚了。

根据您的需要,您需要使用轮廓样式和框阴影的组合。

return (
<Pressable style={(state) => [styles.default, state.focused && styles.focusOutline]}>
  <Text style={{fontWeight: "bold"}}>
    Outline styles only
  </Text>
  <Text>Tab: Colored offset outline</Text>
  <Text>Press: n/a</Text>
</Pressable>
)
// styles
const styles = StyleSheet.create({
  default: {
    paddingHorizontal: 15,
    paddingVertical: 10,
    backgroundColor: "powderblue",
    alignItems: "center",
    borderRadius: 20,
  },
  focusOutline: {
    outlineStyle: "solid",
    outlineWidth: 4,
    outlineColor: "skyblue", 
    outlineOffset: 2,
  }
});

世博小吃


推荐阅读