react native访问本机原生相机
时间: 2023-09-04 15:08:21 浏览: 103
react-native 的原生传感器访问_Java_代码_相关文件_下载
5星 · 资源好评率100%
要访问本机原生相机,你可以使用React Native内置的CameraRoll组件或者使用第三方库如react-native-camera。下面是使用CameraRoll组件的示例代码:
```javascript
import React, { useState } from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Button,
Image,
CameraRoll,
} from 'react-native';
const App = () => {
const [image, setImage] = useState(null);
const handlePress = async () => {
try {
const result = await CameraRoll.getPhotos({ first: 1 });
const photo = result.edges[0].node.image.uri;
setImage(photo);
} catch (error) {
console.log(error);
}
};
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView contentInsetAdjustmentBehavior="automatic" style={styles.scrollView}>
<View style={styles.body}>
<Button title="Take a photo" onPress={handlePress} />
{image && <Image style={styles.image} source={{ uri: image }} />}
</View>
</ScrollView>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: '#fff',
},
body: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
image: {
width: 200,
height: 200,
marginVertical: 20,
},
});
export default App;
```
这个示例代码中,我们使用了CameraRoll组件的getPhotos方法来获取相机拍摄照片的URI,并且将其设置为Image组件的source属性。你也可以使用react-native-camera库来访问相机并进行更多的自定义操作。
阅读全文