簡體   English   中英

為什么我在反應原生 TextInput 中從 useRef 得到 NaN

[英]Why I am getting NaN from useRef in react native TextInput

嗨,下面是一個代碼,其中有兩個來自 react-native 的 Text Input 和一個按鈕,當我單擊該按鈕時,結果應該生成這兩個數字來自兩個 Text Input 但我得到Nan

但是代碼應該給我一個數字,這意味着文本輸入

console.log(+refNum1.current.value) // giving me NaN

我相信 your.value 是字符串類型。 使用parseInt() function 將其轉換為 integer。

例如

ParseInt(myNumber)

讓它像這樣

這里的工作示例

import * as React from 'react';
import { Text, View, StyleSheet, TextInput, Button } from 'react-native';

export default function App() {
  const TextInputRef_1 = React.useRef();
  const TextInputRef_2 = React.useRef();
  const [Result, SetResult] = React.useState('');

  const Generate = () => {
    // Do whatever you like with values
    const a = parseInt(TextInputRef_1.current.value);
    const b = parseInt(TextInputRef_2.current.value);

    console.log('Sum = ', a + b);
    console.log('Difference = ', a - b);
    console.log('Product = ', a * b);
    console.log('Division = ', a / b);

    SetResult(
      `Sum = ${a + b}\nDifference =  ${a - b}\nProduct =  ${
        a * b
      }\nDivision =  ${a / b}`
    );
  };

  return (
    <View style={styles.container}>
      <TextInput
        placeholder="Enter 1st Number"
        ref={TextInputRef_1}
        style={styles.TextInput}
      />
      <TextInput
        placeholder="Enter 2nd Number"
        ref={TextInputRef_2}
        style={styles.TextInput}
      />
      <Button title="Generate" onPress={() => Generate()} />

      <Text>{Result}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
    alignItems: 'center',
  },
  TextInput: {
    width: '100%',
    marginBottom: 12,
    borderColor: 'black',
    borderWidth: 1,
    padding: 12,
  },
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM