我正在尝试实现一个简单的货币转换器。我给出了比特币的值,然后我期望得到 BRL(巴西货币)的值。但是,无论如何,我调用 useEffect 来获取当前汇率,然后在另一个函数中,我将 amount(value, in the code) 与汇率相乘。这是代码:
import { View, Text, Pressable, StyleSheet, Button, TextInput } from 'react-native';
import {useState, useEffect} from 'react'
import axios from 'axios'
// You can import supported modules from npm
// or any files within the Snack
export default function App() {
const[valor, setValor] = useState('');
const[resultado, setResultado] = useState(0);
useEffect( () => {
async function fetchBitcoinPrice() {
axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=brl').then(response => {
const result = valor * response.data.bitcoin.brl
setResultado(result)
})
}
fetchBitcoinPrice();
},[valor])
const converterBTC = (valorAtual) =>{
const quantidade = parseFloat(valor);
if(!NaN(quantidade)){
setResultado(resultado*valor);
}
else{
console.log("Entre com uma quantidade valida")
}
//return setResultado
}
return (
<View style = {styles.container}>
<TextInput defaultValue = {valor} style = {styles.caixaTexto} placeholder = "Quantidade de SATS ou BTC" keyboardType = 'number-pad' onChangeText = {converterBTC}>
</TextInput>
<View style = {styles.botoes}>
</View>
<Text>
R${resultado}
</Text>
</View>
);
}
const styles = StyleSheet.create({
botoes:{
flexDirection: 'row',
margin: '50px',
elevation: 3
},
botao:{
backgroundColor: '#d3d3d3',
width: 60,
height: 30,
borderRadius: 10,
margin: 40,
elevation: 20
},
textoBotao:{
color:'#ffffff',
textAlign: 'center',
},
caixaTexto:{
width: 200,
height: 40,
borderRadius: 40,
borderStyle: 'solid',
borderColor: 'orange',
borderWidth: 2,
marginLeft: 50,
elevation: 10
},
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
`````````
Also, I want to know what I can use to show message error in react native, something similar to Toast on Android.
您的
valor
在您的示例中始终为空字符串
首先,你需要改变TextInput
<TextInput
value={valor}
style={styles.caixaTexto}
placeholder="Quantidade de SATS ou BTC"
keyboardType='number-pad'
onChangeText={value => setValor(value)}
/>
通过 TextInput 改变 valor 的值会导致重新计算 useEffect,
resultado
会被改变,在这种情况下 converterBTC
是无用的
但是如果您需要对输入的文本进行一些验证 -> 您可以将检查移至 useEffect