[英]How to toggle React Native Camera Torch on/off
I am working on a React Native app that scans barcodes.我正在开发一个扫描条形码的 React Native 应用程序。 I want to enable the user the toggle the light on and off with the press of a button.
我想让用户通过按下按钮来打开和关闭灯。 Right now the light stays on at all times.
现在灯一直亮着。 Would this be possible with the React Native camera component?
React Native 相机组件可以做到这一点吗? Thank You!
谢谢你!
class CameraScreen extends React.Component {
state = {
isCameraReady: false
};
constructor(props) {
super(props);
this.handleCameraReady = this.handleCameraReady.bind(this);
this.state = {
camera: {
type: RNCamera.Constants.Type.back
}
};
}
handleCameraReady() {
this.setState({
isCameraReady: true
});
}
onBarCodeRead = data => {
this.setState({ scanned: true });
const DATA_SKU = data.data.split("*");
const SKU = DATA_SKU[0];
const STK_ID = DATA_SKU[1] !== undefined ? DATA_SKU[1] : "";
this.setState({ showCamera: false });
this.props.navigation.navigate("Home", {
scanDataSku: SKU,
scanDataStkID: STK_ID
});
};
render() {
return (
<SafeAreaView style={styles.container}>
<RNCamera
style={styles.container}
onBarCodeRead={this.onBarCodeRead}
ref={cam => (this.camera = cam)}
cameraProps={{ captureAudio: false }}
flashMode={
this.state.isCameraReady
? RNCamera.Constants.FlashMode.torch
: RNCamera.Constants.FlashMode.off
}
onCameraReady={this.handleCameraReady}
></RNCamera>
<View style={styles.bottomNav}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("Home")}
style={styles.bottomBtn}
>
<Text style={styles.bottomTxt}>Back</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.bottomBtn}>
<Text style={styles.bottomTxt}>Light</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
}
Yes - I did something similar:是的 - 我做了类似的事情:
toggleTorch()
{
let tstate = this.state.torchon;
if (tstate == RNCamera.Constants.FlashMode.off){
tstate = RNCamera.Constants.FlashMode.torch;
} else {
tstate = RNCamera.Constants.FlashMode.off;
}
this.setState({torchon:tstate})
}
and then set the flash mode to the appropriate state:然后将 flash 模式设置为相应的 state:
<RNCamera
flashMode={this.state.torchon}
...
Here's how I defined the button:这是我定义按钮的方式:
<TouchableOpacity style={styles.toggleTorch} onPress={() => this.toggleTorch() }>
{ this.state.torchon == RNCamera.Constants.FlashMode.off? (
<Image style={styles.iconbutton} source={require('../images/flash.png')} />
) : (
<Image style={styles.iconbutton} source={require('../images/flash-on.png')} />
)
}
</TouchableOpacity
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.