React Native 공부기 1 ~ bind

포인트

bind는 this의 scope를 제어하기 위한 메소드이다.

Real code

Core 부분

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
export default class Stopwatch extends Component {
componentWillMount() {
this.setState({
mainTime: 0,
subTime: 0,
timerOn: false,
})
}
render() {
console.log(this.state)
return (
<View>
<Buttons
startTime={this._startTime}
stopTime={this._stopTime}
stopWatch={this}/>
</View>
);
}
_startTime(){
if (!this.state.timerOn){
var timer = setInterval(() => {
let mainTime = this.state.mainTime
let subTime = this.state.subTime
this.setState({
mainTime: mainTime + 1,
subTime: subTime + 1,
})
}, 100)
this.setState({
timer: timer,
timerOn: true,
})
}
}
_stopTime() {
clearInterval(this.state.timer)
this.setState({
timerOn: false,
})
}
}

위의 코드에서 주목할 부분은 Buttons라는 컴포넌트에 stopWatch={this}즉,
props를 이용하여 this 전체를 건네주고 있다는 점이다.

Buttons 컴포넌트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Buttons extends Component {
render() {
return (
<View style={day1Style.buttons}>
<TouchableOpacity
style={day1Style.button}
onPress={this.props.startTime.bind(this.props.stopWatch)}>
<Text>
start
</Text>
</TouchableOpacity>
<TouchableOpacity
style={day1Style.button}
onPress={this.props.stopTime.bind(this.props.stopWatch)}>
<Text>
End
</Text>
</TouchableOpacity>
</View>
)
}
}

그리고 Buttons라는 component를 보면 TouchableOpacity의 onPress속성에서
this.props.startTime.bind(this.props.stopWatch)로 되어있는것을 알 수 있다.

여기서 왜 bind(this.props.stopWatch)를 해야만 하는가 하면
그냥 this.props.startTime을 실행해버리면
startTime함수 안의 this가 Buttons의 this가 되어버리기 때문이다.

우리가 제어하고 싶은 state는 Stopwatch component에 존재하기 때문에
startTime함수의 this의 scope를 Stopwatch에 bind시켜줄 필요가 있다.

따라서 bind(this.props.stopWatch) 즉, bind(Stopwatch component 전체)로 this를 고정시켜줌으로써
이러한 문제를 해결시켜줄 수 있다.

참조

Share