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

问题描述 投票:1回答:1

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

    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>
  );
}
react-native textinput
1个回答
0
投票

两个原因:

  1. goalInputHandler()中的变量不匹配。传递enteredText但尝试使用enteredGoal
  2. 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>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.