React native 按react native中的按钮时If语句不工作
我正在尝试制作一个电话游戏,用户猜测1到100之间的数字。当按下按钮时,语句是否应该运行并进行一些更改。什么事也没发生。为什么在按下按钮时不执行语句React native 按react native中的按钮时If语句不工作,react-native,React Native,我正在尝试制作一个电话游戏,用户猜测1到100之间的数字。当按下按钮时,语句是否应该运行并进行一些更改。什么事也没发生。为什么在按下按钮时不执行语句 const buttonPressed = () => { if ({num} < {randomNum}) { message = tooLow } else if ({num} > {randomNum}) { message = tooHigh } else if ({num} === {r
const buttonPressed = () => {
if ({num} < {randomNum}) {
message = tooLow
} else if ({num} > {randomNum}) {
message = tooHigh
} else if ({num} === {randomNum}) {
message= correct
Alert.alert('You guessed the number in'+{counter}+'guesses')
}
counter += 1
}
return (
<View style={styles.container}>
<View>{message}</View>
<TextInput
style={styles.textinput}
keyboardType='numeric'
onChangeText={(num) => setNum(num)}
value={num}
/>
<Button onPress={buttonPressed} title="Press me"/>
</View>
);
}
const按钮按下=()=>{
if({num}<{randomNum}){
message=tooLow
}else if({num}>{randomNum}){
消息=太高
}else if({num}==={randomNum}){
消息=正确
Alert.Alert('您猜到了'+{counter}+'guesses'中的数字)
}
计数器+=1
}
返回(
{message}
setNum(num)}
值={num}
/>
);
}
让我们让事情变得更具反应性。
您需要将此组件
设置为内部状态(如果您没有使用或或任何其他状态管理)
大概是这样的:
constructor(props) {
this.state = {
num: 0
}
}
const setNum = (num) => {
this.setState({num});
}
const buttonPressed = () => {
if ({this.props.num} < {randomNum}) {
message = tooLow
counter + 1
} else if ({this.props.num} > {randomNum}) {
message = tooHigh
counter + 1
} else if ({this.props.num} === {randomNum}) {
counter + 1
message= correct
Alert.alert('You guessed the number in'+{counter}+'guesses')
}
}
return (
<View style={styles.container}>
<View>{message}</View>
<TextInput
style={styles.textinput}
keyboardType='numeric'
onChangeText={(num) => this.setNum(num)}
value={this.props.num}
/>
<Button onPress={buttonPressed} title="Press me"/>
</View>
);
}
构造函数(道具){
此.state={
数字:0
}
}
常量setNum=(num)=>{
this.setState({num});
}
按下常量按钮=()=>{
if({this.props.num}<{randomNum}){
message=tooLow
计数器+1
}else if({this.props.num}>{randomNum}){
消息=太高
计数器+1
}else if({this.props.num}==={randomNum}){
计数器+1
消息=正确
Alert.Alert('您猜到了'+{counter}+'guesses'中的数字)
}
}
返回(
{message}
this.setNum(num)}
value={this.props.num}
/>
);
}
控制台中有错误吗?您是否尝试过按下按钮{buttonPressed()}?请创建一个,我在这里看不到许多变量的声明。