[英]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.