728x90
![](https://blog.kakaocdn.net/dn/n7Rwa/btrnB74pQKW/Z4k2WmQSL7DWlaGfgLWYhK/img.png)
어떤 행동을 수행한뒤 포커스를 해당 input 태그에 맞추고 싶다면 ref를 사용하면됩니다.
input;
render(){
return (
<React.Fragment>
<div>{this.state.first}곱하기{this.state.second}는?</div>
<form onSubmit={this.onSubmit}>
<input ref={(c) => {this.input = c;}} type="number" value={this.state.value} onChange={this.onChange}/>
<button>입력!</button>
</form>
<div>{this.state.result}</div>
</React.Fragment>
);
}
해당 랜더 부분에서 input 태그 바로 뒤에 ref라는 속성이 있습니다.
ref={(c) => {this.input = c;}}
ref속성안에 함수를 하나 넣어주었는데요. (c)의 c는 아무거나 넣어줘도 되는 일종의 변수같은것입니다.
{this.input = c;}는 해당 input이 c가 되도록하는 경우인데 this뒤에 input이 무었이냐면 input이라고 선언이 되어있기 떄문에 그냥 input이라고 적었습니다.
선언되어 있는것이 focus라고 한다면 this.focus = c;가 되겠네요.
이제 포커스를 맞추고 싶은 부분에 this.input.focus();를 작성해주시면 초점이 맞춰집니다.
![](https://blog.kakaocdn.net/dn/be6VRb/btrnBXUU8Z1/reFdUm92sy2yTlaWlrRXm1/img.png)
![](https://blog.kakaocdn.net/dn/cnQb0T/btrnHSraKTp/n15d2NJNhmti8fIS3V02QK/img.png)
이제 실행하고 정답을 입력하면 포커스가 input태그에 맞춰져 있습니다.
근데 setState를 할때마다 render가 실행이 되는데 나중에 render가 너무 여러번 실행이 되면 느려질수가 있겠죠?!
근데 앞에서 속성에 들어가있는 함수를 class안에 따로 만들어 두었었는데 속성에 함수를 선언하게 되면 render가 실행될때마다 함수가 계속해서 생겨나기 때문에 느려질수가 있습니다.
<html>
<head>
<meta charset="UTF-8">
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class GuGuDan extends React.Component{
constructor(props){
super(props);
this.state = {
first: Math.ceil(Math.random() * 9),
second: Math.ceil(Math.random() * 9),
value: '',
result: '',
};
}
onSubmit = (e) => {
e.preventDefault();
if(parseInt(this.state.value) === this.state.first * this.state.second){
this.setState((prevState) => {
return {
result: '정답 : ' + prevState.value,
first: Math.ceil(Math.random() * 9),
second: Math.ceil(Math.random() * 9),
value: '',
};
});
this.input.focus();
} else {
this.setState({
result: '떙',
value: '',
});
this.input.focus();
}
};
onChange = (e) => this.setState({value: e.target.value});
input;
onRefInput = (c) => {this.input = c;}
render(){
return (
<React.Fragment>
<div>{this.state.first}곱하기{this.state.second}는?</div>
<form onSubmit={this.onSubmit}>
<input ref={this.onRefInput} type="number" value={this.state.value} onChange={this.onChange}/>
<button>입력!</button>
</form>
<div>{this.state.result}</div>
</React.Fragment>
);
}
}
</script>
<script type="text/babel">
ReactDOM.render(<GuGuDan />, document.querySelector('#root'));
</script>
</body>
</html>
728x90
'SPA > React' 카테고리의 다른 글
[React] 게임으로 배우는 리액트 - Webpack(웹팩) (0) | 2022.05.30 |
---|---|
[React] 게임으로 배우는 리액트 - Hooks (0) | 2022.05.29 |
[React] 게임으로 배우는 리액트 - Fragment, setState (0) | 2022.05.27 |
[React] 게임으로 배우는 리액트 - 구구단게임 만들기 (0) | 2022.05.26 |
[React] 게임으로 배우는 리액트 - 바벨(babel) (0) | 2022.05.25 |