【问题标题】:React-Native - InputText don't lose focusReact-Native - InputText 不会失去焦点
【发布时间】:2017-11-23 20:22:12
【问题描述】:

在我的 React-native 项目中,我使用了一些 TextInput。 我遇到了特定用例的问题。

https://snack.expo.io/B1RCy4Eef

正如您在这个 Snack 项目中看到的那样,我有一个 Orange Square 和一个 TextInput。

当我的 InputText 获得焦点时,我希望它在我点击 View 的另一个组件(例如橙色方块)时失去焦点。

我想要一个不要求我向我的根视图的每个组件或我的根视图本身添加 Keyboard.dismiss() 调用的解决方案.

感谢您的理解和帮助!

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您不必为每个组件添加关闭,只需添加一个全屏视图处理触摸和关闭键盘即可。这是我的代码。

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

    【讨论】:

    • 谢谢! _onClick() 逻辑的更多解释将不胜感激。但这是目前公认的答案:)
    • _onClick 函数处理整个屏幕上的触摸并检查触摸是否在 TextInput 绑定中。如果没有,请关闭键盘。让点 = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY };是触摸坐标。let rect = { x: px, y: py, width, height } 是 TextInput 的边界。 @LouisLecocq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2013-10-02
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    相关资源
    最近更新 更多