[英]React Native, on onPress setting Text values into state
I am trying to build something like a calculator.我正在尝试构建类似计算器的东西。
I have a function onPressDigit, which I call in touchable opacity.我有一个函数 onPressDigit,我称之为可触摸不透明度。
class App extends Component {
state = {
expression: 0,
}
onPressDigit = () => {
this.setState({
expression: //logic here
})
}
render() {
const { expression } = this.state
return (
<View>
<Text>expression: {expression}</Text>
<TouchableOpacity onPress={this.onPressDigit}>
<Text style={{ fontSize: 30, backgroundColor: 'purple' }}>4</Text>
</TouchableOpacity>
</View>
);
}
}
Now, I want when I click 4 (that is the value of the text in touchableOpacity) the text 4, should become the current state value and I see现在,我希望当我点击 4(即 touchableOpacity 中文本的值)文本 4,应该成为当前状态值,我看到
expression: 4表达:4
instead反而
expressions: 0.表达式:0。
Can't figure out the logic for that...想不通这其中的逻辑...
I'll just do it for you lol its not that deep, 我会为你做这件事而不是那么深,
class App extends Component {
constructor(props) {
super(props);
this.state = {
expression: 0,
}
}
onPressDigit = (number) => {
this.setState({
expression: number
})
}
render() {
const { expression } = this.state
return (
<View>
<Text>expression: {expression}</Text>
<TouchableOpacity onPress={() => this.onPressDigit(4)}>
<Text style={{ fontSize: 30, backgroundColor: 'purple' }}>4</Text>
</TouchableOpacity>
</View>
);
}
}
just pass the number as a argument, sorry if its not the most detailed of answers im about to leave work, but all I did was add an argument to the listener, and then passed it the number 4 through on the onPress 只是将数字作为参数传递,对不起,如果它不是最详细的答案即将离开工作,但我所做的只是向听众添加一个参数,然后在onPress上传递数字4
Since you are using es6 you do not need a constructor
由于您使用的是es6,因此不需要构造函数
you need to pass the value through the function parameter 你需要通过函数参数传递值
class App extends Component {
state = {
expression: 0,
}
onPressDigit = (number) => {
//number is the value you want your expression to have
//you can use any name different from number
this.setState({
expression: number
})
}
render() {
const { expression } = this.state
return (
<View>
<Text>expression: {expression}</Text>
{/*create an arrow function that will pass the value of the expression to the function*/}
<TouchableOpacity onPress={() => this.onPressDigit(4)}>
<Text style={{ fontSize: 30, backgroundColor: 'purple' }}>4</Text>
</TouchableOpacity>
</View>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.