在 React-Native 中,TextInput 字段不允许我编辑或输入新文本

In React-Native the TextInput field wont allow me to edit or type new text

我注意到当我尝试在文本输入字段中键入任何内容时,它会自动将其删除。我已经缩小到值字段的问题,并将其注释掉允许我输入文本,但我不确定可能是什么问题。

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

两个原因:

  1. goalInputHandler() 中的变量不匹配。传入 enteredText 但尝试使用 enteredGoal.
  2. goalInputHandler() 没有 return 任何东西。需要用圆括号代替花括号,或者在setEnteredGoal().
  3. 前加上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>
  );
}