https://snack.expo.io/@miralis/eager-cashew
检查components / high.js。 我正在尝试在此处使用“ useState”:
const [number, setNumber] = useState(mid);
但是,当我尝试添加setNumber(mid);时,到higher()和lower()函数,它破坏了代码。 当我的数字25以及我点击更高的数字时,BCS发出警报25050,但必须给出38。 完整代码:
import React from 'react';
import { useState } from 'react';
import { StyleSheet, Text, View, Button, Alert, TextInput } from 'react-native';
export default function High() {
const [number, setNumber] = useState(mid);
const [max, setMax] = useState();
let begin = 0;
let end = max;
let mid = (begin + end) / 2;
function higher() {
begin = mid;
mid = (begin + end) / 2;
alert(JSON.stringify("Your number is higher/lower " + mid.toFixed() + "?"));
setNumber(mid);
}
function lower() {
end = mid;
mid = (begin + end) / 2;
alert(JSON.stringify("Your number is higher/lower " + mid.toFixed() + "?"));
setNumber(mid);
}
function start() {
alert("Ваше число больше / меньше / равно " + mid + "?")
}
return (
<View style={styles.container}>
<Text>{number}</Text>
<View style={styles.start}>
<Button
title='Start'
style={styles.start}
onPress={() => start()} />
<TextInput
style={styles.input}
placeholder='Write num here'
onChangeText={text => setMax(text)}
placeholderTextColor='#fff' />
</View>
<Button
style={styles.button}
onPress={() => {lower()}}
title='Меньше' />
<Button
title='Больше'
style={styles.button}
onPress={() => {higher()}} />
<Button
title=''
style={styles.button}
onPress={() => alert("Легко!")} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
padding: 10
},
start: {
marginBottom: 20,
},
input: {
backgroundColor: '#1E90FF',
color: '#000'
}
});
答案 0 :(得分:0)
我认为您在使用类型方面遇到麻烦。
onChangeText函数采用字符串作为参数(https://reactnative.dev/docs/textinput#onchangetext),但是您需要一个整数。您只需添加 parseInt
<TextInput
style={styles.input}
placeholder='Write num here'
onChangeText={text => setMax(parseInt(text))} //here
placeholderTextColor='#fff'
/>