Оформление значков для размещения в Textinput

#react-native

#react-native

Вопрос:

Как мне правильно оформить это?

Я пытаюсь использовать значок, который я получил из плоских значков в Textinput поле. это проект CLI React native, поэтому изображение сохраняется где-то внутри ресурсов папки. Вот основная проблема, которая находится над текстовым полем ввода, чего не должно быть.

Изображение выглядит примерно так :

пример.png

Я начал задаваться вопросом, что я делаю не так. Мой код выглядит примерно так

 /* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View , Image, TextInput, TouchableOpacity, Alert, Linking} from 'react-native';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

class Login extends Component {

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

    DummyLogin = () =>
    {
        alert('I am a Dummy Login!');
    }

    FunctionLogin = () =>
    {
        const {user} = this.state;
        const {password} = this.state;
        fetch('https://xxxxxxxxxxxxxxxxxxx.000webhostapp.com/rest/login.php',{
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                user: user,
                password: password
              })
        }).then((response) =>response.json())
        .then((responseJson) => {
            if(responseJson === 'OK')
            {
                this.props.navigation.navigate('Announcements');
            }
            else
            {
                Alert.alert(responseJson);
            }
        }).catch((error) =>{
            console.error(error);
        });
    }
  }

  render() 
  {
      return (
      <View style={styles.container}>
        <Image source={{uri:'asset:/logo/436146d3-d290-459b-ae8a-bc5b07eacea1_200x200.png'}}
        style={styles.logo} />

        <Text style={{textAlign:'left',fontSize:40,fontWeight:'bold' ,color: '#030303'}}> Sign In</Text>

        <View>
        <Image
          source={{uri: 'asset:/icons/user.png'}}
          style={styles.imageStyle}
        />
            <TextInput
            placeholder = " Account Number"
            onChangeText={user => this.setState({user})}
            style={styles.input}
            keyboardType='numeric'
            value={this.state.myNumber}
            maxLength={10} 
            />
        </View>

        <View>
        <Image
          source={{uri: 'asset:/icons/lock.png'}}
          style={styles.imageStyle}
        />
            <TextInput
            placeholder = " Password"
            onChangeText={password => this.setState({password})}
            style={styles.input}
            secureTextEntry={true} />
        </View>

        <Text style={{color: '#030303', textAlign: 'center', alignSelf:'stretch'}}
        onPress={() => Linking.openURL('http://google.com')}>
        Forgot Password?
        </Text>

        <View style={styles.space} />
        <TouchableOpacity onPress={() => {DummyLogin();}} style={styles.button}>
        <Text style={styles.loginbtn}> Login </Text>
         </TouchableOpacity>
         <View style={styles.space} />
         <TouchableOpacity onPress={() => {DummyLogin();}} style={styles.Regbutton}>
        <Text style={styles.loginbtn2}> Register </Text>
         </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        justifyContent :"center",
        alignItems:"center"
    },

    input:{
        width:300,
        height:55,
        margin:10,
        fontSize : 16,
        borderBottomColor:'#030303',
        borderBottomWidth: 1,
        marginBottom: 30,
    },

    button:{
        width:300,
        height: 52,
        padding:10,
        borderRadius:10,
        backgroundColor:'#030303',
        alignItems: 'center'
    },

    Regbutton:{
        width:300,
        height:52,
        padding:10,
        borderRadius:10,
        backgroundColor:'#ffffff',
        alignItems: 'center',
        borderWidth : 2,
        borderColor: '#030303'
    },


    loginbtn:{
        color:'#ffff',
        fontSize : 20,
        fontWeight : 'bold'
    },

    loginbtn2:{
        color:'#030303',
        fontSize : 20,
        fontWeight : 'bold'
    },

    logo:{
    width:150,
    height:150
    },

    space: {
        width: 10, 
        height: 10,
      },

      imageStyle: {
        padding: 5,
        margin: 2,
        height: 15,
        width: 15,
        resizeMode: 'stretch',
        marginBottom: 8,
        marginTop : 8,
        alignItems: 'center',
      },
});

export default Login;
 

Обновленный исходный код

Вот обновленный исходный код

 /* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View , Image, TextInput, TouchableOpacity, Alert, Linking} from 'react-native';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

class Login extends Component {

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

    DummyLogin = () =>
    {
        alert('I am a Dummy Login!');
        this.props.navigation.navigate('Home');
    }

    FunctionLogin = () =>
    {
        const {user} = this.state;
        const {password} = this.state;
        fetch('https://xxxxxxxxxxxxx.000webhostapp.com/rest/login.php',{
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                user: user,
                password: password
              })
        }).then((response) =>response.json())
        .then((responseJson) => {
            if(responseJson === 'OK')
            {
                this.props.navigation.navigate('Announcements');
            }
            else
            {
                Alert.alert(responseJson);
            }
        }).catch((error) =>{
            console.error(error);
        });
    }
  }

  render() 
  {
      return (
      <View style={styles.container}>
        <Image source={{uri:'asset:/logo/436146d3-d290-459b-ae8a-bc5b07eacea1_200x200.png'}}
        style={styles.logo} />

        <Text style={{textAlign:'left',fontSize:40,fontWeight:'bold' ,color: '#030303'}}> Sign In</Text>

        <TextInput
            placeholder = " Account Number"
            onChangeText={user => this.setState({user})}
            style={styles.input}
            keyboardType='numeric'
            value={this.state.myNumber}
            maxLength={10} 
            />

        <TextInput
            placeholder = " Password"
            onChangeText={password => this.setState({password})}
            style={styles.input}
            secureTextEntry={true} />

        <Text style={{color: '#030303', textAlign: 'center', alignSelf:'stretch'}}
        onPress={() => Linking.openURL('http://google.com')}>
        Forgot Password?
        </Text>

        <View style={styles.space} />
        <TouchableOpacity onPress={() => {DummyLogin();}} style={styles.button}>
        <Text style={styles.loginbtn}> Login </Text>
         </TouchableOpacity>
         <View style={styles.space} />
         <TouchableOpacity onPress={() => {DummyLogin();}} style={styles.Regbutton}>
        <Text style={styles.loginbtn2}> Register </Text>
         </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        justifyContent :"center",
        alignItems:"center"
    },

    input:{
        width:300,
        height:55,
        margin:10,
        fontSize : 16,
        borderBottomColor:'#030303',
        borderBottomWidth: 1,
        marginBottom: 30,
    },

    button:{
        width:300,
        height: 52,
        padding:10,
        borderRadius:10,
        backgroundColor:'#030303',
        alignItems: 'center'
    },

    Regbutton:{
        width:300,
        height:52,
        padding:10,
        borderRadius:10,
        backgroundColor:'#ffffff',
        alignItems: 'center',
        borderWidth : 2,
        borderColor: '#030303'
    },


    loginbtn:{
        color:'#ffff',
        fontSize : 20,
        fontWeight : 'bold'
    },

    loginbtn2:{
        color:'#030303',
        fontSize : 20,
        fontWeight : 'bold'
    },

    logo:{
    width:150,
    height:150
    },

    space: {
        width: 10, 
        height: 10,
      },

      imageStyle: {
        flexDirection:'row',
        justifyContent:'center',
        padding: 5,
        margin: 2,
        height: 15,
        width: 15,
        resizeMode: 'stretch',
        marginBottom: 8,
        marginTop : 8,
        alignItems: 'center',
      },
});

export default Login;
 

Комментарии:

1. итак, как это должно было выглядеть?

2. @kenmistry, изображение должно находиться в той же строке, что и поля ввода текста

3. я понимаю. вы можете попробовать передать flexDirection prop со row значением в родительский вид, и он должен отображать оба элемента в одной строке.

4. сделано это, все та же проблема. Позвольте мне поделиться обновленным исходным кодом

Ответ №1:

@Evans, я имел в виду внутреннего родителя <View> , например:

 <View style={{flexDirection: 'row'}}>
  <Image
    source={{uri: 'asset:/icons/user.png'}}
    style={styles.imageStyle}
  />
  <TextInput
    placeholder = " Account Number"
    onChangeText={user => this.setState({user})}
    style={styles.input}
    keyboardType='numeric'
    value={this.state.myNumber}
    maxLength={10} 
  />
</View>
 

Если это все еще не работает, вы можете рассмотреть возможность добавления flex реквизитов для обоих <Image> <TextInput> компонентов и .

Комментарии:

1. Все та же проблема, не выравнивается правильно

2. @Evans я вижу. является ли приведенный выше ваш окончательный код? я попытаюсь повторить со своей стороны, чтобы увидеть, что пошло не так.

Ответ №2:

 <View style={{paddingHorizontal:fontSizes.containerSpace,borderRadius:fontSizes.containerSpace/2,marginBottom:fontSizes.containerSpace,borderColor:'#E3E3E3',borderWidth:.85,width:(width - (fontSizes.containerSpace * 2)),backgroundColor: '#FFF',}}> 
                        <TextInput 
                            style={{height:width * 0.123,fontSize:fontSizes.bodySize * .80,fontFamily:fontFamilies.paraFont,color:'#2C2C2C'}}
                            autoCorrect={false}
                            autoCapitalize='none'
                            value={this.props.login.password}
                            secureTextEntry={this.state.passShowEnable}
                            onChangeText={(text)=>this.props.changeMCode2(text)}
                            placeholder="Enter your Password"
                            placeholderTextColor="#E3E3E3" />
                        <View style={{position: 'absolute',right:fontSizes.containerSpace * 1.5, top:0, height:width * 0.123, justifyContent:'center', backgroundColor: '#FFF',}}>
                            {
                                this.state.passShowEnable == true ?
                                <TouchableOpacity onPress={()=> this.setState({passShowEnable: false})}>
                                    <CustomIcon
                                        iconsName = {'unlock'}
                                        colorIcon = {themeColor.primary}
                                        iconSize  = {fontSizes.iconSize * .8}
                                        iconType  = 'feather' />
                                </TouchableOpacity>
                                :
                                <TouchableOpacity onPress={()=> this.setState({passShowEnable: true})}>
                                    <CustomIcon
                                        iconsName = {'lock'}
                                        colorIcon = {themeColor.primary}
                                        iconSize  = {fontSizes.iconSize * .8}
                                        iconType  = 'feather' />
                                </TouchableOpacity>
                            }
                        </View>
                   </View>