如何从文本输入中获取值



我被困在一个看似简单的函数中。 如何从文本输入中获取值(字符串(?

以下是代码的摘录:

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

我在打字时得到打字,但它没有提交任何内容。

知道吗??

提前感谢!

你应该将你的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>

我有同样的问题,我刚刚开始对本机反应,以下解决方案可用于从组件中获取值TextInput

const [input, setInput] = useState(''); 
<TextInput 
style={ styles.textinput }
placeholder='type somthing'
onChange={ (text) => {
console.log(text.nativeEvent.text)
setInput(text.nativeEvent.text)
}
}

defaultValue={ input }
/>
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>
);
}
}

试试这个,你必须像这样使用它:

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

相关内容

  • 没有找到相关文章

最新更新