如何从 TextInput 中获取值
Posted
技术标签:
【中文标题】如何从 TextInput 中获取值【英文标题】:How to get values from TextInput 【发布时间】:2020-05-22 07:36:00 【问题描述】:我陷入了一个看似简单的功能。 (字符串)?
这里是代码的摘录:
const Insert = props =>
const [enteredName, setEnteredName] = useState();
const sendValues = (enteredName) =>
console.log(enteredName);
;
<TextInput
placeholder="Your Name"
blurOnSubmit
autoCorrect=false
maxLength=30
autoCapitalized="words"
placeholderTextColor="#777"
value=enteredName
onChangeText=text => setEnteredSurname(text)
/>
<View>
<Button title="Submit" onPress=sendValues(enteredName) />
我在输入时得到了输入,但它没有提交任何内容。
有什么想法吗??
提前致谢!
【问题讨论】:
【参考方案1】:您应该将 onPress 从表达式转换为函数并初始化您的状态
const Insert = props =>
const [enteredName, setEnteredName] = useState(''); //INIT TO EMPTY
function sendValues(enteredName)
console.log(enteredName);
;
<TextInput
placeholder="Your Name"
blurOnSubmit
autoCorrect=false
maxLength=30
autoCapitalized="words"
placeholderTextColor="#777"
value=enteredName
onChangeText=text => setEnteredSurname(text) />
<View>
<Button title="Submit" onPress=() => sendValues(enteredName) /> //Function not expression
</View>
【讨论】:
【参考方案2】:class AwesomeProject extends Component
constructor(props)
super(props)
this.state =
username: '',
password: '',
_handlePress()
console.log(this.state.username);
console.log(this.state.password);
render()
return (
<ScrollView style=styles.content>
<View style=styles.content>
<Text style=styles.welcome>
Create Account
</Text>
<Text style=styles.textStyle>
Name
</Text>
<TextInput
style=styles.textInputStyle
placeholder="Enter Name"
returnKeyLabel = "next"
onChangeText=(text) => this.setState(username:text)
/>
<Text style=styles.textStyle>
Name
</Text>
<TextInput
style=styles.textInputStyle
placeholder="Enter Name"
returnKeyLabel = "next"
onChangeText=(text) => this.setState(password:text)
/>
<Button
onPress=() => this._handlePress()
style=styles.buttonStyle>
Submit
</Button>
</View>
</ScrollView>
);
【讨论】:
【参考方案3】:试试这个,你必须像这样使用它:
import React, useState from 'react';
import Text, View,TextInput,Button from 'react-native';
export default Example = () =>
const [enteredName, setEnteredName] = useState('');
sendValues = (enteredName) =>
console.log(enteredName);
;
return (
<View>
<Text>Hey</Text>
<TextInput
placeholder="Your Name"
blurOnSubmit
autoCorrect=false
maxLength=30
autoCapitalized="words"
placeholderTextColor="#777"
value=enteredName
onChangeText=text => setEnteredSurname(text) />
<View>
<Button title="Submit" onPress=() => sendValues(enteredName) />
</View>
</View>
);
【讨论】:
以上是关于如何从 TextInput 中获取值的主要内容,如果未能解决你的问题,请参考以下文章
为啥我第二次点击 fileReferencer.browse 按钮后 TextInput 会更新
yii2 如何获取 textInput 值并发送到另一个 textInput
在 React Native Input/TextInput 中输入值时如何更新 JSON 对象值