如何在React Native中使用View组件实现Chevron图形效果
React Native View组件实现Chevron图形方案
- 首先React Native的
borderRadius属性不支持负值,你代码中设置的负圆角完全不会生效,这是原有代码无法得到预期效果的核心原因 - View组件完全可以实现Chevron图形,不需要借助第三方库,针对不同使用场景的实现方式如下:
场景1:纯箭头型雪佛龙(无内部内容)
适合用来做跳转、展开操作的指示箭头,实现代码如下:
import React, { Component } from 'react' import { View } from 'react-native' export class ChevronArrow extends Component { render() { // 可通过调整borderWidth数值修改箭头大小 const arrowSize = { vertical: 12, // 箭头上下高度 horizontal: 18 // 箭头左右宽度 } return ( <View style={{ width: 0, height: 0, borderTopWidth: arrowSize.vertical, borderBottomWidth: arrowSize.vertical, borderLeftWidth: arrowSize.horizontal, borderTopColor: 'transparent', borderBottomColor: 'transparent', borderLeftColor: '#2563eb', // 箭头颜色 // 向左箭头:将borderLeft替换为borderRight,颜色绑定到borderRight // 向上/向下箭头:对应调整上下边框的配置即可 }} /> ) } }
场景2:可容纳内容的雪佛龙容器
匹配你原有代码中需要展示文本的需求,实现思路是用两个透明三角形定位在容器侧边,模拟V形缺口:
import React, { Component } from 'react' import { View, Text } from 'react-native' export class Chevron extends Component { render() { const chevronHeight = 44; // 容器整体高度 const gapSize = 12; // 右侧V形缺口的深度 return ( <View style={{ position: 'relative', width: 120 }}> {/* 主体内容容器 */} <View style={{ height: chevronHeight, backgroundColor: '#2563eb', paddingHorizontal: 16, justifyContent: 'center', borderTopLeftRadius: 4, borderBottomLeftRadius: 4, marginRight: gapSize }} > <Text style={{ color: '#fff' }}>{this.props.item}</Text> </View> {/* 右上角缺口三角形 */} <View style={{ position: 'absolute', right: 0, top: 0, width: 0, height: 0, borderTopWidth: chevronHeight/2, borderRightWidth: gapSize, borderTopColor: '#2563eb', borderRightColor: 'transparent' }} /> {/* 右下角缺口三角形 */} <View style={{ position: 'absolute', right: 0, bottom: 0, width: 0, height: 0, borderBottomWidth: chevronHeight/2, borderRightWidth: gapSize, borderBottomColor: '#2563eb', borderRightColor: 'transparent' }} /> </View> ) } } export default Chevron
内容的提问来源于stack exchange,提问作者Michael Stow
相关产品推荐
相关产品推荐

