gpt4 book ai didi

reactjs - 如何在 React Native 中获取输入值?

转载 作者:行者123 更新时间:2023-12-04 17:54:23 25 4
gpt4 key购买 nike

能否请您告诉我如何获取 input field 值,或者换句话说,点击按钮时的用户名和密码输入字段值。

这是我的代码 https://rnplay.org/apps/drT9vw

import React from 'react';
import {
registerComponent,
} from 'react-native-playground';
import {
Text,
View,
Image,
StyleSheet,
TextInput,
TouchableHighlight
} from 'react-native';

class App extends React.Component {
constructor(props){
super(props);
this.state ={
userName :'',
password:''
};
}

login(){
alert(this.state.userName)
}
OnChangesValue(e){
console.log(e.nativeEvent.text);
this.setState({
userName :e.nativeEvent.text,
})
}

changePassword(e){
console.log(e.nativeEvent.text);
this.setState({
password :e.nativeEvent.text,
})
}

render() {
return (
<View style={styles.container}>

<Text style={styles.heading}> Login</Text>
<TextInput
style={styles.loginInput}
onChange={(text)=> this.setState({userName:text})}
ref="myInput"
underlineColorAndroid='transparent'
placeholder="username !"
/>
<TextInput
style={styles.loginInput}
ref="pass"
onChange={this.changePassword.bind(this)}
underlineColorAndroid='transparent'
placeholder="password to ff!"
secureTextEntry={true}
/>
<TouchableHighlight style={styles.touchable} onPress={this.login.bind(this)}>
<Text style={styles.touchableButton}>Click</Text>
</TouchableHighlight>
</View>

)
}
}

const styles = StyleSheet.create({
container: {
backgroundColor: '#EF501E',
flex: 1,
alignItems: 'center',
padding :20
},
logo: {
width: 50,
height: 50
},
heading: {
fontSize: 30,
marginTop: 20
},
loginInput: {
height: 50,
alignSelf: 'stretch',
borderWidth: 1,
borderColor: '#33090C',
flexDirection: 'row',
justifyContent: 'center',
marginBottom:10
},
touchable:{
backgroundColor:'#2E18DD',
height:40,
alignSelf:'stretch',
alignItems:'center',
justifyContent:'center'

},
touchableButton:{
color:'#fff',
fontSize:10
}
});

registerComponent(App);

更新

login(){
alert(this.refs.myInput.value)
}

它给出未定义的

最佳答案

没有得到确切的问题,你将用户名和密码存储在状态变量中。因此,您可以通过 this.state.userNamethis.state.password 获取值。或者你也可以使用 refs 来获取这样的值:this.refs.myInput.value

改变这个乐趣:

changePassword(text){
console.log(text);
this.setState({
password :text,
})
}

在 tutorialspoint 上查看相同的示例:https://www.tutorialspoint.com/react_native/react_native_text_input.htm

关于reactjs - 如何在 React Native 中获取输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com