React Native 画虚线 DashLine

本文介绍了一种在React Native中实现虚线的方法。通过计算屏幕宽度并创建多个视图组件来模拟虚线效果,支持水平和垂直方向的虚线显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

React Native刚开始做,没有虚线控件,也没有Android中xml画虚线方便,可以用下面办法来实现。

实现思路:
1.拿到一个宽度width,求出虚线长度len
2.生成一个数组arr,(后面会根据数组元素画n个view,组合成虚线)
3.生成虚线

import React from 'react';
import {
    Text,
    View,
    StyleSheet,
    Dimensions,
} from 'react-native';
const screenWidth = Dimensions.get('window').width;

export default class DashLine extends Component{
    render(){
        var len = Math.ceil(screenWidth/4);
        var arr = [];
        for(let i=0; i<len; i++){
            arr.push(i);
        }

        return <View style={styles.dashLine}>
            {
                arr.map((item, index)=>{
                    return <Text style={styles.dashItem} key={'dash'+index}> </Text>
                })
            }
        </View>
    const styles = StyleSheet.create({
    dashLine: {
        flexDirection: 'row',
    },
    dashItem: {
        height: 1,
        width: 2,
        marginRight: 2,
        flex: 1,
        backgroundColor: '#ddd',
    }
})

这里是水平方向的虚线 ,要是垂直方向的虚线,只需要修改下 dashLine,dashItem的样式

const styles = StyleSheet.create({
    dashLine: {
        flexDirection: 'column',
    },
    dashItem: {
        height: 2,
        width: 1,
        marginRight: 2,
        flex: 1,
        backgroundColor: '#ddd',
    }
})

const screenWidth = Dimensions.get(‘window’).width;修改为:

const screenHeight = Dimensions.get('window').height;

虚线就定义好了

使用:

   <View style={{ overflow: 'hidden',
        backgroundColor: '#999',
        margin: 10}}><DashLine/></View>
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值