[React Native -6] 버튼 눌렀을 때 증가, 감소
+, - 버튼을 눌렀을 때 판매개수 증가, 감소 구현하기
React에서 프로젝트를 했을 때 이를 구현해본 적이 있다. ReactNative에도 똑같이 적용해보았다
먼저, state 값에 itemCount를 변수로 두고, 초기값을 1로 두었다
React와 마찬가지로 state는 값이 변경될 때 마다 컴포넌트가 다시 렌더링되기 때문에 동적인 데이터를 다룰 때 사용된다
class PutGoods extends Component{
constructor(props){
super(props);
this.state={
itemCount:1,
}
}
}
+,- 버튼을 클릭했을 때 state변수 itemCount이 1씩 증가하거나 감소해야 한다
따라서 버튼 onPress에서 setState를 사용해 함수를 구현해준다
+버튼을 눌렀을 때는 this.state.itemCount+1 의 값을 변수 itemCount에 넘겨준다
- 버튼을 눌렀을 때는 this.state.itemCount-1 의 값을 변수 itemCount에 넘겨준다
<View style={styles.item}>
<View style={styles.item1}>
<Text>판매개수</Text>
</View>
<View style={styles.item2}>
<Text style={styles.text_count}>{this.state.itemCount}</Text>
</View>
<View style={styles.item3}>
<TouchableOpacity activeOpacity={0.8} style={styles.btn_count} onPress={()=>{this.setState({itemCount:this.state.itemCount+1})}}>
<Text style={styles.btn_text}>+</Text>
</TouchableOpacity>
</View>
<View style={styles.item4}>
<TouchableOpacity activeOpacity={0.8} style={styles.btn_count} onPress={()=>{this.setState({itemCount:this.state.itemCount-1})}}>
<Text style={styles.btn_text}>-</Text>
</TouchableOpacity>
</View>
</View>
- React에서 state에 직접 접근해서 값을 바꾸면 안된다 따라서 setState를 사용하여 itemCount변수에 증가한 값을 다시 저장해준다
- Button 컴포넌트는 안드로이드, ios에서 다르게 보이기 때문에 관리하는 데에 어려움이 있기때문에 대신에 TouchableOpacity 컴포넌트를 사용했다 (activeOpacity는 깜빡인 정도를 나타낸다)
이렇게 증가, 감소하는 것을 볼 수 있습니다. 하지만 - 버튼을 계속 눌렀을 때 판매개수가 음수까지 내려가는 것을 볼수있다
❓ 판매개수는 0이하가 되면 안되므로 제한을 주려면 어떻게 해야할까
<TouchableOpacity activeOpacity={0.8} style={styles.btn_count} onPress={this.minusNum}>
minusNum=()=>{
if(this.state.itemCount <= 1){
this.setState({itemCount:1})
Alert.alert('1개이상 등록해야합니다')
}
else{
this.setState({itemCount:this.state.itemCount-1});
}
}
onPress의 minusNum이라는 함수를 따로 구현하였다
if, else문으로 itemCount가 1이하일때 itemCount를 1으로 초기화해주고, Alert 컴포넌트를 이용해서 경고문이 뜨도록 하였다
*Alert컴포넌트 쓰려면 import해주는거 잊지말기
결과물
다음으로는 드롭다운을 구현해보겠다