简体   繁体   English

通过本机反应传递复选框值以显示/隐藏密码

[英]Passing checkbox value to show / hide Password via react native

I'm using Firebase auth I will want to add a Check box, it will display the password in the password text box and hide it when it is clicked again我正在使用 Firebase auth 我会想添加一个复选框,它将在密码文本框中显示密码并在再次单击时隐藏它

How to Passing checkbox value to show / hide Password?如何传递复选框值以显示/隐藏密码?

This is my Login Page Code:这是我的登录页面代码:

export default class Login extends Component {
    constructor(props) {
        super(props)
        this.state = {
            email: '',
            password: '',
            response: ''
        }
        this.signUp = this.signUp.bind(this)
        this.login = this.login.bind(this)
    }

    async signUp() {
        try {
            await firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
            this.setState({
                response: 'Account Created!'
            })
            setTimeout(() => {
                this.props.navigator.push({
                    id: 'App'
                })
            }, 500)
        } catch (error) {
            this.setState({
                response: error.toString()
            })
        }
    }
    async login() {
        try {
            await firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
            this.setState({
                response: 'user login in'
            })

            setTimeout(() => {
                this.props.navigator.push({
                    id: 'App'
                })
            })

        } catch (error) {
            this.setState({
                response: error.toString()
            })
        }
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.containerInputes}>
                    <TextInput
                        placeholderTextColor="gray"
                        placeholder="Email"
                        style={styles.inputText}
                        onChangeText={(email) => this.setState({ email })}
                    />
                    <TextInput
                        placeholderTextColor="gray"
                        placeholder="Password"
                        style={styles.inputText}
                        password={true}
                        secureTextEntry={true}
                        onChangeText={(password) => this.setState({ password })}
                    />
                </View>
                <TouchableHighlight
                    onPress={this.login}
                    style={[styles.loginButton, styles.button]}
                >
                    <Text
                        style={styles.textButton}
                    >Login</Text>
                </TouchableHighlight>
                <TouchableHighlight
                    onPress={this.signUp}
                    style={[styles.loginButton, styles.button]}
                >
                    <Text
                        style={styles.textButton}
                    >Signup</Text>
                </TouchableHighlight>
            </View>
        )
    }
}

One way of doing that is to set a state variable like showPassword and toggle it whenever the checkbox is checked.一种方法是设置像 showPassword 这样的状态变量,并在选中复选框时切换它。 Like so:像这样:

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

export default class DemoProject extends Component {
  constructor(props) {
    super(props);
    this.toggleSwitch = this.toggleSwitch.bind(this);
    this.state = {
      showPassword: true,
    }
  }

  toggleSwitch() {
    this.setState({ showPassword: !this.state.showPassword });
  }

  render() {
    return (
      <View>
        <TextInput
          placeholderTextColor="gray"
          placeholder="Password"
          secureTextEntry={this.state.showPassword}
          onChangeText={(password) => this.setState({ password })}
        />
        <Switch
          onValueChange={this.toggleSwitch}
          value={!this.state.showPassword}
        /> 
        <Text>Show</Text>
      </View>
    )
  }
}

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

NOTE: This won't work if you set the password prop!!!注意:如果您设置了密码道具,这将不起作用!!!

So just use a regular TextInput and utilize the secureTextEntry prop.因此,只需使用常规TextInput并利用secureTextEntry道具即可。

import React, {useState} from 'react';
import {TextInput} from 'react-native';

import Icon from 'react-native-vector-icons/FontAwesome5';

const [hidePass, setHidePass] = useState(true);
    
    <TextInput
              placeholder="Old password"
              autoCompleteType="password"
              secureTextEntry={hidePass ? true : false}
            />
            <Icon
              name={hidePass ? 'eye-slash' : 'eye'}
              size={15}
              color="grey"
              onPress={() => setHidePass(!hidePass)}
            />

here is my way of doing it这是我的做法

const LoginScreen = props => {
  const [icon, setIcon] = useState("eye-off")
  const [hidePassword, setHidePassword] = useState(true)

  _changeIcon = () => {
    icon !== "eye-off"
      ? (setIcon("eye-off"), setHidePassword(false))
      : (setIcon("eye"), setHidePassword(true))
  }

i used native base for textInput我为 textInput 使用了原生基础

 <Input
              secureTextEntry={hidePassword}
              placeholder="Password"
              placeholderTextColor={palette.gray}
            />
            <Icon name={icon} size={20} onPress={() => _changeIcon()} />

this will change the secureTextEntry on click这将在单击时更改 secureTextEntry

Please correct me if I am wrong, are you asking how to create a check box?如果我错了,请纠正我,您是在问如何创建复选框吗? If so, you have two routes, either use a 3rd party library from one of the many check boxes on the web or you can create one yourself.如果是这样,您有两条路线,要么使用来自网络上众多复选框之一的 3rd 方库,要么您可以自己创建一个。

Steps:步骤:

  1. download a icon library as such https://github.com/oblador/react-native-vector-icons so you can use the two material design icons from enter link description here eg.下载一个图标库,例如https://github.com/oblador/react-native-vector-icons,这样你就可以使用这里输入链接描述中的两个材料设计图标,例如。 checkbox-blank-outline and checkbox-marked to emulate clicked and not clicked checkbox-blank-outline 和 checkbox-marked 模拟点击和未点击
  2. using those two new icons, simply create a new component with what ever functionality you desire and handle all states and such the way you want.使用这两个新图标,只需创建一个具有您想要的功能的新组件,并以您想要的方式处理所有状态。

Basic implementation:基本实现:

  1. Have a state that controls if it was checked or not有一个状态来控制它是否被选中
  2. Have a onPress function to handle both states and trigger the respective props有一个 onPress 函数来处理这两种状态并触发相应的道具
// the on press function
onPress = () => {
  if (this.sate.checked) {
    this.props.checked();
  } else {
    this.props.unChecked();
  }
}

// the rendered component
<Icon name={this.state.checked ? "checkbox-marked" : "checkbox-blank-outline" onPress={this.onPress}/>

this is how i did in simple way,这就是我以简单的方式所做的,

my checkbox and password component,我的复选框和密码组件,

<input style={ inputUname } type={this.state.type} placeholder="Password" value={ this.state.password } onChange={this.handlePassword}/>
<Checkbox defaultChecked={false} onSelection={this.showPassword} value="false" name="Checkbox" label="Show password"/>

my state,我的状态,

this.state = {
     type: 'input'
}

here is my show password event,这是我的表演密码事件,

showPassword(e){
    this.setState( { showpassword: !this.state.showpassword }) // this is to change checkbox state
    this.setState( { type: this.state.type === 'password' ? 'text' : 'password' }) // this is to change input box type text/password change
}

enter image description here在此处输入图像描述

  const [password, setPassword] = useState("")
    const [passwordVisible, setPasswordVisible] = useState(true)



<TextInput
    mode='outlined'
    style={{ flex: 1, marginHorizontal: 20, marginTop: 30 }}
    autoCapitalize="none"
    returnKeyType="next"
    label=' Password '
    keyboardType="default"
    underlineColorAndroid={'rgba(0,0,0,0)'}
    right={<TextInput.Icon color={colors.white} name={passwordVisible ? "eye" : "eye-off"} onPress={onPressEyeButton} />}
    text='white'
    maxLength={50}
    onChangeText={(text) => { setPassword(text) }}
    value={password}
    defaultValue={password}
    theme={styles.textInputOutlineStyle}
    secureTextEntry={passwordVisible}
    />


 textInputOutlineStyle: {
    colors: {
        placeholder: colors.white,
        text: colors.white, 
        primary: colors.white,
        underlineColor: 'transparent',
        background: '#0f1a2b'
    }
},

[1]: https://i.stack.imgur.com/C7ist.png [1]:https://i.stack.imgur.com/C7ist.png

Step1:Create a "useState" hook to store the initial values of password and secureTextEntry

    const [data, setData] = useState({
                password: '',
                isSecureTextEntry: true,
              });

Step2:Update the state according to the conditions 
        <View>
        <TextInput
                    style={styles.textInput}
                    placeholder="Enter Password"
                    secureTextEntry={data.isSecureTextEntry ? true : false}
                    onChangeText={data => {
                      setData({
                        password: data,
                        //OR
                        /*
                          //Array destructuring operator to get the existing state i.e
                          ...data
                        */
                        //and then assign the changes
                        
                        isSecureTextEntry: !data.isSecureTextEntry,
                      });
                    }}></TextInput>
                  <TouchableOpacity
                    onPress={() => {
                      setData({
                        //...data,
                        isSecureTextEntry: !data.isSecureTextEntry,
                      });
                    }}>
                    <FontAwesome
                      name={data.isSecureTextEntry ? 'eye-slash' : 'eye'}
                      color="gray"
                      size={25}
                      paddingHorizontal="12%"
                    />
                  </TouchableOpacity>
                </View>
<View>
  <Input
    style={styles.input}
    onChangeText={onChangeData}
    multiline={false}
    secureTextEntry={!showPassword}
    textContentType={"password"}
    value={data.password}
    placeholder="Password"
  />

  <TouchableHighlight
    style={{
      textAlign: "right",
      position: "absolute",
      right: 20,
      bottom: 22,
      zIndex: 99999999,
    }}
    onPress={() => setShowPassword(!showPassword)}
  >
    <>
      {showPassword && (
        <Ionicons name="eye-outline" size={22} color="#898A8D" />
      )}
      {!showPassword && (
        <Ionicons name="eye-off-outline" size={22} color="#898A8D" />
      )}
    </>
  </TouchableHighlight>
</View>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应本机复选框纸不单独检查 - React native checkbox paper not checking individually 通过 rest api 在本机反应中通知 - Notification via rest api in react native 无法隐藏在 AWS Authenticator 之前显示的本机启动画面 - Not able to hide react native splashscreen shown before AWS Authenticator React Native Expo - 根据用户是否登录显示不同的 NavigationContainer - React Native Expo - show different NavigationContainer depending on whether user is logged in or not React Native Firebase 动态链接通过 iMessage 发送不正确 - React Native Firebase dynamic links send improperly via iMessage React Native如何获取useRef current的值 - How to get the value of useRef current in React Native 为什么 react firebase 钩子在使用 email 和密码登录时无法显示错误? - Why react firebase hook do not working to show error in sign in with email and password? 在 Firebase 云消息传递中,React 本机应用程序未通过 TOPIC 接收通知 - React native app not receiving notifications via TOPIC in Firebase cloud messaging 将视频上传到 firestore react native 时如何显示上传百分比 - How to show upload percentage when uploading video to firestore react native 图片不显示在 Notification React Native Firebase - Image Doesn't show in Notification React Native Firebase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM