admin管理员组文章数量:1277910
I'm new to learning React / React Native and have run into the following issue. When tapping on the <TouchableWithoutFeedback>
element, the view does not increment.
Code below:
class SingleHabit extends Component {
constructor() {
super();
this.state = {count: 0};
}
_incrementCount() {
this.setState = ({
count: count + 1
});
}
render () {
return (
<TouchableWithoutFeedback onPress={ () => this._incrementCount() }>
<View
style= {[
styles.singleHabit,
{backgroundColor: this.props.color}
]}
>
<Text style={styles.habitNameText}>{this.props.text}</Text>
<Text style={styles.countText}>{this.state.count}</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
Also, in the interest of self-learning, if there's anyway you would refactor this (or just simply better ways of doing things), I'd love to hear!
I'm new to learning React / React Native and have run into the following issue. When tapping on the <TouchableWithoutFeedback>
element, the view does not increment.
Code below:
class SingleHabit extends Component {
constructor() {
super();
this.state = {count: 0};
}
_incrementCount() {
this.setState = ({
count: count + 1
});
}
render () {
return (
<TouchableWithoutFeedback onPress={ () => this._incrementCount() }>
<View
style= {[
styles.singleHabit,
{backgroundColor: this.props.color}
]}
>
<Text style={styles.habitNameText}>{this.props.text}</Text>
<Text style={styles.countText}>{this.state.count}</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
Also, in the interest of self-learning, if there's anyway you would refactor this (or just simply better ways of doing things), I'd love to hear!
Share Improve this question asked May 18, 2017 at 22:35 AmzAmz 131 gold badge1 silver badge3 bronze badges2 Answers
Reset to default 6this
inside your incrementCount function isn't automatically bound to the class. If you change it to use arrow functions, then the scope of this
bees the class. Also its good practice to use the optional function setState if you want to modify state based offa previous state values:
_incrementCount = () => {
this.setState(prevState => ({ count: prevState.count + 1 }));
}
Your _incrementCount
function is wrong.
- You are not calling
this.setState
never. You are assign({count: count + 1})
tothis.setState
. Correct it removing the=
. - The
count
used in the expressioncount + 1
is not defined. Change it tothis.state.count
.
.
Summarizing, Change
_incrementCount() {
this.setState = ({
count: count + 1
});
}
to
_incrementCount() {
this.setState({
count: this.state.count + 1
});
}
本文标签: javascriptReact Native Increment State onPressStack Overflow
版权声明:本文标题:javascript - React Native Increment State onPress - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741231370a2362166.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论