React Native:如何为View模拟onBlur和onFocus事件

时间:2017-02-23 18:51:23

标签: react-native

在React Native中,只有TextInput具有onFocusonBlur事件侦听器。但是,我们希望在View上模拟此效果。

这是我们努力实现的目标。屏幕上有View。它获得了#34;焦点"当用户点击它并突出显示时。我们希望检测到用户点按View之外的内容,以便我们可以“模糊”#34; View,即删除突出显示。

我知道我们可以使用focus方法(https://facebook.github.io/react-native/docs/nativemethodsmixin.html#focus)来请求View的焦点。问题是我不知道如何检测用户是否在View之外按下。

1 个答案:

答案 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.