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

vwoqyblh  于 2022-12-14  发布在  React
关注(0)|答案(8)|浏览(144)

我正在使用Firebase auth,我想添加一个复选框,它将在密码文本框中显示密码,并在再次单击时隐藏密码
如何传递复选框值以显示/隐藏密码?

这是我的登录页面代码:

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

xriantvc1#

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="Password"
      secureTextEntry={hidePass ? true : false}>
       <Icon
          name={hidePass ? 'eye-slash' : 'eye'}
          onPress={() => setHidePass(!hidePass)} />
    <TextInput/>
1aaf6o9v

1aaf6o9v2#

一种方法是设置一个状态变量,比如showPassword,并在复选框被选中时切换它。

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

注意:如果您设置了密码prop,则此操作无效!!!

因此,只需使用常规的TextInput并利用secureTextEntry属性。

ar7v8xwq

ar7v8xwq3#

这是我的做法

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

我对textInput使用了本机基

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

这将更改单击时的secureTextEntry

mtb9vblg

mtb9vblg4#

如果我说错了,请纠正我,你是在问如何创建一个复选框吗?如果是这样,你有两个路线,要么使用网络上众多复选框之一的第三方库,要么你可以自己创建一个。
操作步骤:
1.下载一个图标库,如https://github.com/oblador/react-native-vector-icons,这样你就可以使用enter link description here中的两个材质设计图标,如checkbox-blank-outline和checkbox-marked,以模拟单击和未单击
1.使用这两个新图标,只需创建一个新的组件,它具有您想要的任何功能,并以您想要的方式处理所有状态。
基本实施:
1.具有控制是否选中的状态
1.使用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}/>
iyfamqjs

iyfamqjs5#

这就是我简单方法,
我复选框和密码组件,

<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"/>

我州,

this.state = {
     type: 'input'
}

下面是我“显示密码"事件,

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
}
to94eoyn

to94eoyn6#

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

oiopk7p5

oiopk7p57#

第一步:创建一个useState钩子来存储passwordsecureTextEntry的初始值:

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

步骤2:根据条件更新状态:

<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>
5jdjgkvh

5jdjgkvh8#

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

相关问题