【问题标题】:React Native: how to simulate onBlur and onFocus event for ViewReact Native:如何模拟 View 的 onBlur 和 onFocus 事件
【发布时间】:2017-04-10 11:28:04
【问题描述】:

在 React Native 中,只有 TextInputonFocusonBlur 事件监听器。但是,我们想在View 上模拟这种效果。

这是我们努力实现的目标。屏幕上有一个View。当用户点击它并突出显示时,它会获得“焦点”。我们想检测到用户在View之外点击,这样我们就可以“模糊”View,也就是去掉高亮。

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

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我认为最简单的方法是设置一个状态变量,以便您可以使用该变量,例如:

    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>
          );
      }
    }
    

    您可以使用MyView,其中要求为&lt;MyView /&gt;,数组views 上的每个项目都可以具有所需的任何样式,并通过访问this.state.activeView 来配置每个是否处于活动状态。

    如果您有任何问题,请告诉我。

    【讨论】:

      【解决方案2】:

      在这种情况下,我将onPress() 添加到相关View 之外的元素中。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-30
        • 1970-01-01
        • 2017-07-15
        • 2017-02-25
        相关资源
        最近更新 更多