React Native中CSS菱形与三角形绝对定位点击交互问题
问题:CSS形状点击区域异常,如何实现带交互的复杂图形?
我用CSS技巧和absolute定位属性创建了一个由菱形和三角形组成的复杂结构图,希望每个菱形和三角形都可点击,但由于CSS三角形基于边框实现的特性,点击行为不符合预期。

图中包含一个菱形和两个三角形。
期望的点击行为
- 点击A、B、E区域时,触发菱形的点击事件
- 点击C、D区域时,触发第一个三角形(图中编号2)的点击事件
实际的点击行为
- 点击A区域无响应(怀疑是
absolute和transform属性导致) - 点击B区域时,触发第一个三角形的点击事件(原因是第一个三角形的透明右侧边框)
- 点击C区域时,触发第二个三角形(图中编号3)的点击事件(原因是第二个三角形的透明顶部边框)
- 点击D区域时,触发第一个三角形的点击事件(符合预期)
- 点击E区域时,触发菱形的点击事件(符合预期)
请问如何实现这类包含多个此类形状的复杂交互图案?是否应该考虑使用图片/SVG替代CSS形状?我还需要在每个形状中添加多个动态数字/文本/表情符号。
以下是简化的代码片段:
import React from 'react'; import { View, TouchableOpacity, StyleSheet, SafeAreaView, } from 'react-native'; const MyComplexDiagram = ({navigation, route}) => { const clickShape = text => { console.log('clicked: ', text); }; return ( <SafeAreaView style={{flex: 1}}> <View> <TouchableOpacity onPress={() => clickShape("rhombus")}> <View style={[styles.rhombus]} /> </TouchableOpacity> <TouchableOpacity onPress={() => clickShape("first triangle")}> <View style={[styles.firstTriangle]} /> </TouchableOpacity> <TouchableOpacity onPress={() => clickShape("second triangle")}> <View style={[styles.secondTriangle]} /> </TouchableOpacity> </View> </SafeAreaView> ); }; export default MyComplexShape; const styles = StyleSheet.create({ rhombus: { position: 'absolute', top: 50, left: 100, width: 100, height: 100, backgroundColor: 'green', transform: [{rotate: '45deg'}], }, firstTriangle: { position: 'absolute', top: 0, left: 0, backgroundColor: 'transparent', borderStyle: 'solid', borderLeftWidth: 50, borderRightWidth: 50, borderTopWidth: 50, borderLeftColor: 'transparent', borderRightColor: 'transparent', borderTopColor: 'red', }, secondTriangle: { position: 'absolute', top: 0, left: 0, backgroundColor: 'transparent', borderStyle: 'solid', borderLeftWidth: 50 * Math.sqrt(2), borderTopWidth: 50 * Math.sqrt(2), borderBottomWidth: 50 * Math.sqrt(2), borderLeftColor: 'black', borderBottomColor: 'transparent', borderTopColor: 'transparent', } });
内容的提问来源于stack exchange,提问作者yoyostar
相关产品推荐
相关产品推荐

