问题描述
我想在我的Expo相机中使用构造函数,但是构造函数在功能中不起作用。 也许有想法如何在相机中使用构造函数?
只需要在我的相机上构造构造函数,也许还有其他想法?
将此代码放入相机,例如:
constructor(props) {
super(props);
this.state = {
reptile: 'alligator',color: '#008f68',};
}
摄像机代码:
import React,{ useState,useEffect } from 'react';
import { Text,View,TouchableOpacity } from 'react-native';
import { Camera } from 'expo-camera';
export default function App() {
const [hasPermission,setHasPermission] = useState(null);
const [type,setType] = useState(Camera.Constants.Type.back);
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}>
<View
style={{
flex: 1,backgroundColor: 'transparent',flexDirection: 'row',}}>
<TouchableOpacity
style={{
flex: 0.1,alignSelf: 'flex-end',alignItems: 'center',}}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}>
<Text style={{ fontSize: 18,marginBottom: 10,color: 'white' }}> Flip </Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
解决方法
您可以为功能组件编写自己的自定义钩子
useConstructorHook
function useConstructor(callBack = () => {}) {
const [hasBeenCalled,setHasBeenCalled] = useState(false);
if (hasBeenCalled) return;
callBack();
setHasBeenCalled(true);
}
将此内容包含在您的应用中并像这样使用
import React,{ useState,useEffect } from 'react';
import { Text,View,TouchableOpacity } from 'react-native';
import { Camera } from 'expo-camera';
function useConstructor(callBack = () => {}) {
const [hasBeenCalled,setHasBeenCalled] = useState(false);
if (hasBeenCalled) return;
callBack();
setHasBeenCalled(true);
}
export default function App() {
useConstructor(() => {
console.log(
"This only happens ONCE and it happens BEFORE the initial render."
);
});
const [hasPermission,setHasPermission] = useState(null);
const [type,setType] = useState(Camera.Constants.Type.back);
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}>
<View
style={{
flex: 1,backgroundColor: 'transparent',flexDirection: 'row',}}>
<TouchableOpacity
style={{
flex: 0.1,alignSelf: 'flex-end',alignItems: 'center',}}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}>
<Text style={{ fontSize: 18,marginBottom: 10,color: 'white' }}> Flip </Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}