簡體   English   中英

在 React Native 中取消對 TextInput 的關注

[英]Unfocus a TextInput in React Native

我正在使用 React Native 構建一個 Android 應用程序。

如何強制TextInput為“unFocus”,這意味着 cursor 在文本字段內閃爍。 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

}

   })

這對真實用戶來說可能無關緊要,但我只是在模擬,如果我想重新加載,這很煩人。

更好的方法是使用ScrollViewKeyboard.dismiss 通過在用戶點擊 textInput 外部時使用ScrollView ,鍵盤被解除。 這樣做是因為keyboardShouldPersistTaps 的ScrollView默認屬性是never 這是用戶期望的行為。 為了關閉鍵盤,或者它相當於模糊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 官方文檔中的完整示例。

我設法用 this.ref 參考解決了這個問題。 首先,您為 TextInput 分配一個ref ,如下所示:

<input ref="myInput" />

然后,您從函數中調用 blur() 方法到this.refs.myInput

 blurTextInput(){
    this.refs.myInput.blur()
 }

實際上找到了它。它看起來不那么漂亮,我的直覺說這不是一個非常“反應”的解決方案,但如果你想要它就在這里。

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

我的用例有點不同。 用戶不會直接在輸入字段中輸入值。 該字段主要用於捕獲用戶嘗試輸入值並打開模式的嘗試。 我想在模態關閉后模糊該字段,以減少用戶稍后必須執行的額外點擊。

如果使用 Hooks,你可以做一些簡單的事情

const inputRef = useRef(null);

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

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

inputRef.current.blur();

Noah 上面的回答很有效,但現在不鼓勵在 React 中使用字符串引用,並且可能很快就會被棄用。 相反,您應該使用一個回調函數,該函數在您要引用的組件呈現時被調用。

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

如果您使用 Flow,則可以通過在渲染函數之外放置類似的內容來指定 ref 的類型:

textInputRef: ?TextInput;

如果您想在提交后失去焦點,請使用 blurOnSubmit 屬性。

它做它需要的

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM