【问题标题】:React Native TextInput does not display number type valueReact Native TextInput 不显示数字类型值
【发布时间】:2020-08-09 11:07:53
【问题描述】:

我有一个总是必须是数字类型的预渲染值。我将 TextInput 值设置为此数字,但除非我将数字转换为字符串,否则它不会显示在输入字段中。但是,当使用 toString() 或 String(value) 将数字转换为字符串时,通过清除字段来编辑 TextInput 会导致在字段中显示 NaN,由于每次尝试后都会重复出现,因此无法清除。

TextInput 的外观如下:

<TextInput value={5}/> 
//displays nothing in the field unless when like this: 

<TextInput value="5"/>

<TextInput value={value.toString()}/>  and <TextInput value={String(value}/> cause NaN when the field is cleared completely

它也不会发出数字值,但不渲染数字值是更严重的问题。

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您可以通过使用字符串文字来简化此操作。

    你有

    const [num, setNum] = React.useState(0);
    

    然后,

    <TextInput 
       keyboardType="numeric" 
       onChangeText={(newNum) => setNum(newNum)} 
       defaultValue={`${num}`} />
    

    【讨论】:

      【解决方案2】:

      不渲染数值是更严重的问题。

      TextInput 的 value prop type 是 string ,这就是为什么在将它作为 prop 传递给 TextInput 时必须显式转换它的原因。

      for more info

      您可以通过使用 state 和 onTextChange 方法检查代码 sn-p 来实现。

      import * as React from 'react';
      import { Text, View, StyleSheet ,TextInput} from 'react-native';
      import Constants from 'expo-constants';
      
      
      export default function App() {
        const [numValue,setNumValue] = React.useState(9991122)
        return (
          <View style={styles.container}>
            <TextInput value={numValue.toString()} keyboardType={'numeric'} style={{margin:100,borderWidth:2}} onChangeText={(e)=>setNumValue(e)}/> 
          </View>
        );
      }
      
      const styles = StyleSheet.create({
        container: {
          justifyContent: 'center',
          paddingTop: Constants.statusBarHeight,
          backgroundColor: '#ecf0f1',
          padding: 8,
        },
       
      });
      

      【讨论】:

      • 谢谢@muhammad。这适用于 useState。但是,我正在使用formik。请问您知道如何使用 handleChange 发出数字而不是字符串吗?还是其他方法?
      猜你喜欢
      • 2022-12-23
      • 2021-06-15
      • 2018-06-21
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多