React Native 进度条组件实现教程
这里提供一个简单的示例代码,你可以根据自己的需求进行修改和定制:
import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
const ProgressBar = ({ progress }) => {
const [width, setWidth] = useState(0);
const onLayout = event => {
const { width: layoutWidth } = event.nativeEvent.layout;
setWidth(layoutWidth);
};
const progressWidth = width * progress;
return (
<View style={styles.container} onLayout={onLayout}>
<View style={[styles.progress, { width: progressWidth }]} />
<Text style={styles.text}>{Math.round(progress * 100)}%</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
width: '100%',
height: 20,
backgroundColor: '#eee',
borderRadius: 10,
overflow: 'hidden',
},
progress: {
height: '100%',
backgroundColor: '#4caf50',
},
text: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
textAlign: 'center',
textAlignVertical: 'center',
color: 'white',
fontWeight: 'bold',
},
});
export default ProgressBar;
// 使用示例
import React, { useState } from 'react';
import { View, Button } from 'react-native';
import ProgressBar from './ProgressBar';
const App = () => {
const [progress, setProgress] = useState(0);
const increaseProgress = () => {
setProgress(prevProgress => prevProgress + 0.1);
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ProgressBar progress={progress} />
<Button title='Increase Progress' onPress={increaseProgress} />
</View>
);
};
export default App;
本示例代码展示了如何创建一个简单的进度条组件,它根据提供的进度值动态调整进度条的宽度,并显示当前的进度百分比。你可以在你的 React Native 应用中使用这个组件来显示文件上传进度、下载进度、任务完成度等信息。
原文地址: https://www.cveoy.top/t/topic/mwOX 著作权归作者所有。请勿转载和采集!