我注意到当我尝试在文本输入字段中键入任何内容时,它会自动将其删除。我已将问题缩小为值字段,并对其进行注释可以输入文本,但我不确定可能是什么问题。
import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
export default function App() {
const [enteredGoal, setEnteredGoal] = useState('');
const goalInputHandler = (enteredText) => {
setEnteredGoal(enteredGoal);
};
const addGoalHandler = () => {
console.log(enteredGoal);
};
return (
<View style={styles.screen}>
<View style={styles.inputContainer}>
<TextInput
placeholder="Course Goal"
style={styles.input}
onChangeText={goalInputHandler}
value={enteredGoal}
/>
<Button title='Add' onPress={addGoalHandler} />
</View>
<View />
</View>
);
}
两个原因:
goalInputHandler()
中的变量不匹配。传递enteredText
但尝试使用enteredGoal
。goalInputHandler()
不返回任何内容。您需要使用括号而不是花括号,或在setEnteredGoal()
之前添加return语句。正确的代码:
import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
export default function App() {
const [enteredGoal, setEnteredGoal] = useState('');
const goalInputHandler = (enteredText) => (
setEnteredGoal(enteredText);
);
const addGoalHandler = () => (
console.log(enteredGoal);
);
return (
<View style={styles.screen}>
<View style={styles.inputContainer}>
<TextInput
placeholder="Course Goal"
style={styles.input}
onChangeText={goalInputHandler}
value={enteredGoal}
/>
<Button title='Add' onPress={addGoalHandler} />
</View>
<View />
</View>
);
}