React Native: how to simulate onBlur and onFocus event to view

In React Native, only TextInput has an onFocus and onBlur event listener. However, we would like to simulate this effect on the View .

This is what we are trying to achieve. There is a View on the screen. It gets “focus” when the user clicks on it and is lit. We want to find that the user is disconnected outside the View , so that we can “blur” the View , that is, remove the selection.

I know that we can use the focus method ( https://facebook.imtqy.com/react-native/docs/nativemethodsmixin.html#focus ) to request focus for the View . The problem is that I do not know how to detect that the user clicks the View button.

+6
source share
2 answers

I think the easiest way is to set a state variable so that you can play with it, for example:

 class MyView extends Component { constructor(props) { super(props); this.state = { activeView: null, } this.views = [ (<View style={{ padding: 20 }}><Text>View 1</Text></View>), (<View style={{ padding: 20 }}><Text>View 2</Text></View>), (<View style={{ padding: 20 }}><Text>View 3</Text></View>), (<View style={{ padding: 20 }}><Text>View 4</Text></View>), (<View style={{ padding: 20 }}><Text>View 5</Text></View>), ]; } _setActive( index ) { return () => { this.setState({ activeView: index }) } } render() { return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> {this.views.map( (view, index) => { let containerStyle = []; if ( index === this.state.activeView ) { containerStyle.push({ borderWidth: 10 }) } return ( <TouchableOpacity onPress={this._setActive(index)} style={containerStyle}> {view} </TouchableOpacity> ); })} </View> ); } } 

You can use MyView , where requried as <MyView /> also each element of the views array can have any desired style and each can be configured if it is active, only by accessing this.state.activeView .

Let me know if you have any questions.

+3
source

In such situations, I add onPress() to an element that is outside the scope of the View question.

<View onPress(removeHighlight)></View> <View onPress(addHighlight)></View>

+1
source

Source: https://habr.com/ru/post/1015225/


All Articles