Как я могу поместить значок внутри TextInput в React Native?
Я думаю иметь что-то вроде этого https://android-arsenal.com/details/1/3941, где у вас есть значок, который вы нажимаете для отображения пароля как открытого текста, а не как точки. Однако мне не удалось найти какой-либо пользовательский компонент, который бы мне помог.
Я не хочу тратить слишком много времени на такую второстепенную функцию, поэтому я спрашиваю, не предприняв ничего еще: есть ли какой-то пользовательский компонент, который я пропустил? Если нет, есть ли простой способ добавить детей в TextInput? Или я должен просто иметь TextInput и Touchable бок о бок?
Ответы
Ответ 1
Вы можете использовать комбинацию View, Icon и TextInput, например:
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/>
<TextInput
style={styles.input}
placeholder="User Nickname"
onChangeText={(searchString) => {this.setState({searchString})}}
underlineColorAndroid="transparent"
/>
</View>
и используйте гибкое направление для стилизации
searchSection: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
searchIcon: {
padding: 10,
},
input: {
flex: 1,
paddingTop: 10,
paddingRight: 10,
paddingBottom: 10,
paddingLeft: 0,
backgroundColor: '#fff',
color: '#424242',
},
Иконки были взяты из "иконки с реакцией-native-vector-vector"
Ответ 2
По сути, вы не можете поместить значок внутри textInput, но вы можете подделать его, обернув его внутри представления и установив некоторые простые правила стиля.
Вот как это работает:
- поместите Icon и TextInput в родительский вид
- установите flexDirection для родителя в 'row, чтобы выровнять дочерние элементы рядом друг с другом
- дать TextInput flex 1, чтобы он занимал всю ширину родительского представления
- дать родительскому View вид borderBottomWidth и сдвинуть эту границу с помощью paddingBottom (это сделает его похожим на обычный textInput с borderBottom)
- (или вы можете добавить любой другой стиль в зависимости от того, как вы хотите, чтобы он выглядел)
Код:
<View style={styles.passwordContainer}>
<TextInput
style={styles.inputStyle}
autoCorrect={false}
secureTextEntry
placeholder="Password"
value={this.state.password}
onChangeText={this.onPasswordEntry}
/>
<Icon
name='what_ever_icon_you_want'
color='#000'
size={14}
/>
</View>
Стиль:
passwordContainer: {
flexDirection: 'row',
borderBottomWidth: 1,
borderColor: '#000',
paddingBottom: 10,
},
inputStyle: {
flex: 1,
},
(Примечание: значок находится под TextInput, поэтому он отображается в крайнем правом углу, если он был выше TextInput, он отображался бы слева.)
Ответ 3
Вы можете использовать этот модуль, который прост в использовании: https://github.com/halilb/react-native-textinput-effects
Ответ 4
Вы можете обернуть ваш TextInput
в View
.
<View>
<TextInput/>
<Icon/>
<View>
Ответ 5
//This is an example code to show Image Icon in TextInput//
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, TextInput, Image } from 'react-native';
//import all the components we are going to use.
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<View style={styles.SectionStyle}>
<Image
//We are showing the Image from online
source={{uri:'http://aboutreact.com/wp-content/uploads/2018/08/user.png',}}
//You can also show the image from you project directory like below
//source={require('./Images/user.png')}
//Image Style
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1 }}
placeholder="Enter Your Name Here"
underlineColorAndroid="transparent"
/>
</View>
<View style={styles.SectionStyle}>
<Image
//We are showing the Image from online
source={{uri:'http://aboutreact.com/wp-content/uploads/2018/08/phone.png',}}
//You can also show the image from you project directory like below
//source={require('./Images/phone.png')}
//Image Style
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1 }}
placeholder="Enter Your Mobile No Here"
underlineColorAndroid="transparent"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
margin: 10,
},
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
borderWidth: 0.5,
borderColor: '#000',
height: 40,
borderRadius: 5,
margin: 10,
},
ImageStyle: {
padding: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
});
Экспо
Ответ 6
Здесь у вас есть пример, который я взял из своего собственного проекта, я только что удалил то, что, как я думал, нам не понадобилось для примера.
import React, { Component } from 'react';
import {
Text,
TouchableOpacity,
View,
StyleSheet,
Dimensions,
Image
} from 'react-native';
class YourComponent extends Component {
constructor(props) {
super(props);
this._makeYourEffectHere = this._makeYourEffectHere.bind(this);
this.state = {
showPassword: false,
image: '../statics/showingPassImage.png'
}
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={this._makeYourEffectHere}>
<Text>button</Text>
<Image style={styles.image} source={require(this.state.image)}></Image>
</TouchableOpacity>
<TextInput password={this.state.showPassword} style={styles.input} value="abc" />
</View>
);
}
_makeYourEffectHere() {
var png = this.state.showPassword ? '../statics/showingPassImage.png' : '../statics/hidingPassImage.png';
this.setState({showPassword: !this.state.showPassword, image: png});
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center',
},
button: {
width: Dimensions.get('window').width * 0.94,
height: 40,
backgroundColor: '#3b5998',
marginTop: Dimensions.get('window').width * 0.03,
justifyContent: 'center',
borderRadius: Dimensions.get('window').width * 0.012
},
image: {
width: 25,
height: 25,
position: 'absolute',
left: 7,
bottom: 7
},
input: {
width: Dimensions.get('window').width * 0.94,
height: 30
}
});
module.exports = YourComponent;
Надеюсь, это поможет вам.
Сообщите мне, было ли это полезно.
Ответ 7
Это работает для меня в ReactNative 0.60.4
Посмотреть
<View style={styles.SectionStyle}>
<Image
source={require('../assets/images/ico-email.png')} //Change your icon image here
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1 }}
placeholder="Enter Your Name Here"
underlineColorAndroid="transparent"
/>
</View>
Стили
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
borderWidth: 0.5,
borderColor: '#000',
height: 40,
borderRadius: 5,
margin: 10,
},
ImageStyle: {
padding: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
}