我陷入了一个看似简单的功能。 如何从TextInput获取值(字符串)?
以下是代码的摘录:
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)} />
我在打字时得到打字但没有提交任何东西。
有什么想法吗?
谢谢!
答案 0 :(得分:0)
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>
);
}
}
答案 1 :(得分:0)
您应该将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 :(得分:0)
尝试一下,您必须像这样使用它:
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>
);
}