【发布时间】:2018-12-05 21:26:08
【问题描述】:
我正在尝试在拍摄后显示图像,现在就在相机下方。但是,我拍完图片后,图片变量本身就被初始化为:Promise { "_40": 0,"_55": null,"_65": 0,"_72":null,},而且图片的uri/path都是未定义的。 _maybeRenderImage() 函数旨在仅在从相机初始化后才显示图像。
相机工作正常,我什至看到窗口重新调整了图像的大小,但只有一个白屏而不是图像。我究竟做错了什么?是否与异步调用和takePicture 函数有关?任何帮助表示赞赏!
const StyledCenterView = styled(View)`
justify-content: center;
align-items: center;
flex: 1;
`;
interface CameraState {
permissionsGranted: boolean;
image: any;
type: any;
}
class CameraView extends React.Component<any, CameraState> {
camera:any = null;
constructor(props: any) {
super(props);
this.state = {
permissionsGranted: null,
image: null,
type: Camera.Constants.Type.back,
};
}
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ permissionsGranted: status === 'granted' });
}
takePicture = () => {
if (this.camera) {
const photo = this.camera.takePictureAsync();
console.log(photo.uri);
console.log(photo.path);
this.setState({ image: photo });
}
}
_maybeRenderImage = () => {
const { image } = this.state;
if (image) {
console.log('got an image!');
return <Image
source={{ uri: image.uri }}
style={{ width: 250, height: 250 }} />;
} else {
console.log('no image in state');
}
}
render() {
const { permissionsGranted } = this.state;
if (permissionsGranted === null) {
return <Text>Access not asked for</Text>;
} else if (permissionsGranted === false) {
return <Text>Change permissions to allow camera usage!</Text>;
} else {
return(
<View flex>
<Camera
ref={(ref:any) => {
this.camera = ref;
}}
style={{ flex: 1 }}>
</Camera>
<TouchableOpacity
onPress={this.takePicture}
style={{ alignSelf: 'center' }}>
<Ionicons name="ios-radio-button-on" size={70} color="black" />
</TouchableOpacity>
{this._maybeRenderImage()}
</View>
);
}
}
}
export default CameraView;
【问题讨论】:
-
它返回异步Promise,所以试试这个方法:jsfiddle.net/a3gvb8ok
标签: reactjs react-native camera uri expo