在React Native中,只有TextInput
具有onFocus
和onBlur
事件侦听器。但是,我们希望在View
上模拟此效果。
这是我们努力实现的目标。屏幕上有View
。它获得了#34;焦点"当用户点击它并突出显示时。我们希望检测到用户点按View
之外的内容,以便我们可以“模糊”#34; View
,即删除突出显示。
我知道我们可以使用focus
方法(https://facebook.github.io/react-native/docs/nativemethodsmixin.html#focus)来请求View
的焦点。问题是我不知道如何检测用户是否在View
之外按下。
答案 0 :(得分:4)
I think the easiest is to set a state variable instead so you can play with that one such as:
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 every item on the array views
can have any style required and configure each if is active just by access to this.state.activeView
.
Let me know if you have any question.