javascript - React Native 中的 Expo-camera 无法正常工作
问题描述
我正在尝试使用 React 本机应用程序访问相机。我已经从官方文档中复制了所有代码。每个人都做了同样的事情,包括官方的 expo-docs https://docs.expo.io/versions/latest/sdk/camera/。我访问相机和拍照的代码是
export default function Cameracontrol() {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
async function takePicture() {
console.log(this.camera)
if (this.camera) {
console.log('Pictactue Taken')
let photo = await this.camera.takePictureAsync();
}
else {
console.log('Caera Not Open');
}
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission === null) {
return <View />;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={type}
ref={camera => this.camera = camera}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<View style={{ flex: 1, flexDirection: "row", justifyContent: "space-between", margin: 20 }}>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}>
<Ionicons
name="ios-photos"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={takePicture}
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}>
<FontAwesome
name="camera"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}>
<MaterialCommunityIcons
name="camera-switch"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
</View>
</View>
</Camera>
</View>
);
}
我遇到以下错误。
undefined is not an object (evaluating '_this.camera = camera')
此错误与行密切相关
ref={camera => this.camera = camera}
通过删除这行代码,错误也被删除了。
如果有男孩能帮我解决这个问题,我真的很感激。
解决方案
你在一个功能组件中,而不是一个类。因此,您不能使用this
. 此外,ref
不像在课堂上那样工作。
你应该使用useRef
:https ://reactjs.org/docs/hooks-reference.html#useref
const inputEl=useRef(null);
<input ref={inputEl} type="text" />
推荐阅读
- java - Java LocalDate 如何将一年中的最后一周作为第 53 周而不是新年的第 1 周?
- bash - 即使构建未成功运行也不会获得构建失败状态(云构建远程构建器)
- python-3.x - 如何针对每个索引项从 Dataframe 访问列表中的项目?
- javascript - 如何从 html5 画布上的图像中检测特定边缘并将图像保存在特定边缘内
- sql - 如何在 SQL 中选择数字从先前记录增加的行
- ios - 如何检测状态栏 iOS 13 上的触摸
- c# - 将日志写入列表时服务器代码错误 403
- laravel - 无法删除与 Laravel 中的外键链接的其他表中的数据
- javascript - 如何使用 SSO oauth 2.0 登录,然后存储令牌以从邮递员自动化脚本运行所有其他 API?
- css - 如何使用 not 选择器来定位 ID 内的元素?