Reputation: 1814
In my React-native project, I'm using some TextInput. I'm having an issue a with specific use-case.
https://snack.expo.io/B1RCy4Eef
As you can see in this Snack project, i'm having an Orange Square and a TextInput.
When my InputText is focused, i'd like it to lose focus when i'm tapping on another component of my View like, for instance, the orange square.
I'd like a solution that doesn't requires me to add a Keyboard.dismiss() call to every component of my root View or my root View itself.
Thanks for your understanding && your help !
Upvotes: 0
Views: 1735
Reputation: 1823
you don't have to add dismiss to every component, only add one full screen View handling touch and dismiss keyboard will work.here is my codes。
render() {
return (<View style={styles.container} >
<View style={{height: 300, width: 300, backgroundColor: 'orange'}}>
</View>
<Text style={styles.paragraph}>
Thanks for your time !
Tap the InputText and try to lose focus while tapping on the
Square above
</Text>
<TouchableOpacity
style={{position:"absolute",
backgroundColor:"rgba(0,0,0,0)",
opacity:0,
width:Dimensions.get('window').width,
height:Dimensions.get('window').height,
left:0,
top:0}}
onPress= {this._onClick.bind(this)}/>
<TextInput
value={this.state.inputValue}
ref={(c)=>this._textInput = c}
onChangeText={this._handleTextChange}
autoCorrect={false}
style={{ width: 200, height: 50, borderWidth: 1, padding: 8 }}
/>
</View>
);
}
_isContainInRect(rect, point){
return point.x >= rect.x && point.x <= rect.x + rect.width && point.y >=
rect.y && point.y <= rect.y + rect.height;
}
_onClick(e){
console.log("............onclick")
let a = e.nativeEvent;
let point = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY };
this._textInput.measure((fx, fy, width, height, px, py) => {
let rect = { x: px, y: py, width, height }
if (!this._isContainInRect(rect, point)) {
console.log("will dismiss....")
dismissKeyboard();
}
});
}
Upvotes: 2