React-Class Ref

설명

  • ref는 걍 Html Id랑 비슷함. 컴포넌트 별로 지정하는 Id.
state = { text: '' }

// 버튼 클릭하면 ref로 인풋 불러와서 값 출력함.
handleClick = (e) => {
  console.log(this.textInput.value);
}
<button onClick={this.handleClick}></button>

// input 값 업데이트
handleChange = (e) => {
  this.setState({ text: e.target.value });
}
<input
  type="text"
  value={this.state.text}
  onChange={this.handleChange}
  ref={(ref) => {this.textInput=ref}} // ref 지정하는 방법
/>

좋은 웹페이지 즐겨찾기