import React, { Component } from 'react';
class App extends Component {
// 버튼을 누르면 this.inputRef에 저장된 input의 DOM 정보를 보여준다
// 결과 : <input>
handleOnClick = () => console.log(this.inputRef);
render() {
return <div>
{/* input의 요소를 this.inputRef에 연결 */}
<input ref={(ref) => this.inputRef = ref} />
<button onClick={this.handleOnClick}>Click</button>
</div>
}
}
export default App;
current라는 객체에 정보가 담겨서 제공된다.
import React, { Component, createRef } from 'react';
class App extends Component {
// createRef로 ref 생성
inputRef = createRef();
// 버튼을 누르면 this.inputRef에 저장된 input의 DOM 정보를 보여준다
// 결과 : { current : input }
handleOnClick = () => console.log(this.inputRef);
render() {
return <div>
{/* input의 요소를 this.inputRef에 연결 */}
<input ref={this.inputRef} />
<button onClick={this.handleOnClick}>Click</button>
</div>
}
}
export default App;
import React, { Component, createRef } from 'react';
// 버튼을 클릭하면 input에 focus를 해준다.
class App extends Component {
inputRef = createRef();
handleOnClick = () => this.inputRef.current.focus();
render() {
return <div>
<input ref={this.inputRef}/>
<button onClick={this.handleOnClick}>Click</button>
</div>
}
}
export default App;
import React, { Component, createRef } from 'react';
class App extends Component {
// createRef로 ref 생성
inputBoxRef = createRef();
// App에서 만든 버튼 핸들러 함수로 ref를 이용하여 자식 컴포넌트의 메소드를 사용할 수 있다.
handleAppOnClick = () => this.inputBoxRef.current.handleOnClick();
render() {
return <React.Fragment>
{/* 컴포넌트에 직접 App 컴포넌트에서 생성한 ref를 연결한다. */}
<InputBox ref={this.inputBoxRef} />
<button onClick={this.handleAppOnClick}>App</button>
</React.Fragment>
}
}
// 자식 컴포넌트
class InputBox extends Component {
inputRef = createRef();
handleOnClick = () => this.inputRef.current.focus();
render() {
return <div>
<input ref={this.inputRef}/>
<button onClick={this.handleOnClick}>Click</button>
</div>
}
}
export default App;
import React, { Component } from 'react';
class App extends Component {
state = {
text: ''
}
handleOnChange = (e) => this.setState({ text: e.target.value });
handleOnClick = () => console.log(this.state.text);
render() {
return <div>
<input onChange={this.handleOnChange}/>
<button onClick={this.handleOnClick}>Click</button>
</div>
}
}
export default App;
import React, { Component, createRef } from 'react';
class App extends Component {
state = {
text: ''
}
inputRef = createRef();
handleOnClick = () => {
this.setState({
text: this.inputRef.current.value
}, () => console.log(this.state.text));
}
render() {
return <div>
<input ref={this.inputRef}/>
<button onClick={this.handleOnClick}>Click</button>
</div>
}
}
export default App;