【问题标题】:In React-Native the TextInput field wont allow me to edit or type new text在 React-Native 中,TextInput 字段不允许我编辑或输入新文本
【发布时间】:2019-10-23 01:01:49
【问题描述】:

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

    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】:

    两个原因:

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

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多