在 React Native 中取消对 TextInput 的关注

Unfocus a TextInput in React Native

我正在使用 React Native 构建一个 Android 应用程序。

如何将 TextInput 强制为 "unFocus",这意味着光标在文本字段内闪烁。有 isFocused()onFocus() 的功能,但我如何真正让文本字段放弃焦点。你会认为一旦我按下回车键它就会自动执行,但事实并非如此。

   import React, {Component} from 'react';
   import { AppRegistry, Text, View, StyleSheet, TextInput, TouchableOpacity} 
   from 'react-native';

   var SHA256 = require("crypto-js/sha256");

   export default class LoginForm extends Component{


constructor(props){
    super(props);
    this.state = {
        email: '',
        password:''
    };
}

tryLogin = () => {
    if(this.state.email=="email123" && this.state.password == "password"){
        console.log("password verified");
        this.props.navigator.replace({
            title: 'Dashboard'
        });
    }

    console.log(this.state.email);
    console.log(this.state.password);
    console.log("Hash" + SHA256(this.state.password));
}

render(){
    return(
        <View style={styles.container}>
            <TextInput 
                style={styles.input}

                placeholder="Email address" 
                placeholderTextColor="white"
                onChangeText={(email) => this.setState({email})}>
            </TextInput>
            <TextInput style={styles.input} 
                placeholder="Password" 
                placeholderTextColor="white" 
                secureTextEntry
                onChangeText={(password) => this.setState({password})}>
            </TextInput>

            <TouchableOpacity style={styles.loginButtonContainer} onPress={this.tryLogin}>
                <Text style={styles.loginButtonText}>LOGIN</Text>
            </TouchableOpacity>
        </View>
  );
}
}

AppRegistry.registerComponent('LoginForm', () => LoginForm);

const styles =  StyleSheet.create({
container: {
    padding: 20
},
input:{
    height: 40,
    backgroundColor: '#e74c3c',
    marginBottom: 20,
    color: 'white',
    paddingHorizontal: 15,
    opacity: .9
},
loginButtonContainer:{
    justifyContent: 'center',
    backgroundColor: '#bc4c3c',
    paddingVertical:15

},
loginButtonText:{
    textAlign:'center',
    color:'white',
    fontWeight: '700',
    fontSize: 24

}

   })

这对真实用户来说可能无关紧要,但我只是在模拟,如果我想重新加载,这很烦人。

发现它 actually.It 看起来不太漂亮,我的直觉告诉我这不是一个很好的 "react" 解决方案,但如果你想要它,它就是。

<TextInput 
 style={styles.input} 
 ref="email_input"
 onSubmitEditing={() => this.refs['email_input'].blur()} 
 placeholder="Email address" 
 placeholderTextColor="white"
 onChangeText={(email) => this.setState({email})}/>

更好的方法是使用ScrollViewKeyboard.dismiss。通过使用 ScrollView,当用户在 textInput 之外点击时,键盘被关闭。这是因为 ScrollView 默认 属性 for keyboardShouldPersistTapsnever。这是用户期望的行为。为了关闭键盘,或者等效地模糊 textInput,当用户点击登录按钮时,将 Keyboard.dismissed() 添加到tryLogin 函数。

import React, {Component} from 'react';
import { AppRegistry, Text, View, StyleSheet, TextInput, TouchableOpacity, ScrollView, Keyboard}
  from 'react-native';
var SHA256 = require("crypto-js/sha256");

export default class LoginForm extends Component{


  constructor(props){
    super(props);
    this.state = {
      email: '',
      password:''
    };
  }

  tryLogin = () => {
    Keyboard.dismiss();
    if(this.state.email=="email123" && this.state.password == "password"){
      console.log("password verified");
      this.props.navigator.replace({
        title: 'Dashboard'
      });
    }

    console.log(this.state.email);
    console.log(this.state.password);
    console.log("Hash" + SHA256(this.state.password));
  }

  render(){
    return(
      <ScrollView style={styles.container}>
        <TextInput
          style={styles.input}

          placeholder="Email address"
          placeholderTextColor="white"
          onChangeText={(email) => this.setState({email})}>
        </TextInput>
        <TextInput style={styles.input}
                   placeholder="Password"
                   placeholderTextColor="white"
                   secureTextEntry
                   onChangeText={(password) => this.setState({password})}>
        </TextInput>

        <TouchableOpacity style={styles.loginButtonContainer} onPress={this.tryLogin}>
          <Text style={styles.loginButtonText}>LOGIN</Text>
        </TouchableOpacity>
      </ScrollView>
    );
  }
}

AppRegistry.registerComponent('LoginForm', () => LoginForm);

const styles =  StyleSheet.create({
  container: {
    padding: 20
  },
  input:{
    height: 40,
    backgroundColor: '#e74c3c',
    marginBottom: 20,
    color: 'white',
    paddingHorizontal: 15,
    opacity: .9
  },
  loginButtonContainer:{
    justifyContent: 'center',
    backgroundColor: '#bc4c3c',
    paddingVertical:15

  },
  loginButtonText:{
    textAlign:'center',
    color:'white',
    fontWeight: '700',
    fontSize: 24

  }

})

您可以使用键盘 API。

import { Keyboard, TextInput } from 'react-native';

<TextInput
  onSubmitEditing={Keyboard.dismiss}
/>

请参阅 react native offical document 中的完整示例。

我设法通过 this.ref 参考解决了这个问题。 首先,您将 ref 分配给 TextInput,如下所示:

<input ref="myInput" />

然后,您从函数

调用 blur() 方法 this.refs.myInput
 blurTextInput(){
    this.refs.myInput.blur()
 }

works well, but using string refs is now discouraged in React,并且可能很快就会被弃用。相反,您应该使用回调函数,该函数在您要引用的组件呈现时被调用。

<TextInput 
  ref={(c: any) => {
    this.textInputRef = c;
  }}
  onSubmitEditing={() => this.textInputRef.blur()} 
/>

如果您使用的是 Flow,则可以通过在渲染函数之外放置类似这样的内容来指定引用的类型:

textInputRef: ?TextInput;

我的用例有点不同。用户不会直接在输入字段中输入值。该字段主要用于捕获用户输入值并改为打开模式的尝试。我想在模式关闭后模糊该字段,以减少用户稍后必须进行的额外点击。

如果使用 Hooks,你可以做一些简单的事情

const inputRef = useRef(null);

<Input
  ref={inputRef}
  {...props}
/>

然后在任何需要的地方调用它。

inputRef.current.blur();

如果您想在提交后失去焦点,请使用 blurOnSubmit 属性。

<TextInput 
   blurOnSubmit={true}
   //other props
/>

它做它需要的

function TextInputCustom({ placeholder, style }) {

    React.useEffect(() => {
        const keyboardHide = Keyboard.addListener('keyboardDidHide', () => {
            Keyboard.dismiss();
        });
        return () => {
            keyboardHide.remove()
        }
    }, []);
    return (
        <TextInput
            style={style}
            placeholder={placeholder}            
        />
    )
}

export default TextInputCustom;

我使用了下面的代码,它非常适合我: 我将所有视图包装在 TouchableWithoutFeedback 和 onPress={() => {Keyboard.dismiss();}}

 import {View,TouchableWithoutFeedback,Keyboard,} from 'react-native';
 ......
<SafeAreaView>
  <ScrollView nestedScrollEnabled={true}>
    <TouchableWithoutFeedback
      onPress={() => {Keyboard.dismiss();}}>
      <View style={styles.container}>
      {/* ..... */}
      </View>
    </TouchableWithoutFeedback>
  </ScrollView>
</SafeAreaView>

TextInput 的父组件 View 包装在 Pressable 组件中,然后将 Keyboard.dismiss 传递给 onPress 属性。因此,如果用户点击 TextInput 字段外的任意位置,将触发 Keyboard.dismiss,这将导致 TextInput 字段失去焦点并隐藏键盘。

<Pressable onPress={Keyboard.dismiss}>
  <View>
    <TextInput
      multiline={true}
      onChangeText={onChangeText}
      value={text}
      placeholder={...}
     />
   </View>
</Pressable>