import React,{Component} from "react";
import '../App.css'
class ValidationSample extends Component{
state={
password:'',
clicked:false,
validated:false
}
handleChange = e => {
this.setState({
password: e.target.value
})
}
handleButtonClick = () =>{
this.setState({
clicked:true,
validated:this.state.password ==='0000'
})
}
render(){
return (
<div>
<input
type="password"
value ={this.state.password}
onChange={this.handleChange}
className={this.state.clicked ?
(this.state.validated ? 'success':'failure'): ''}
/>
<button onClick={this.handleButtonClick}>검증하기</button>
</div>
)
}
}
export default ValidationSample
버튼이 onClick
이 되면 clicked
이 되었다라고 바뀌고, validated
가 '0000'이면 true 아니면 false
input
창에서
onChange
로 적을 때마다 password가 바뀌게 해주었다.className
을 지정해줘서 style이 변하게 만들어 줬다 → this.state.clicked ?
→ 클릭이 되어있다면 this.state.validated?
유효성 검사가 true 인지 아닌지 확인 후 'success' or 'failure' 로 반환한다 → 클릭이 안되어있다면 빈값 반환<input ref={(ref) => {this.변수명=ref}} />
this.변수명
은 input요소의 DOM을 가리킨다.
import React,{Component} from "react";
class RefSample extends Component{
input = React.createRef()
handleFocus= () =>{
this.input.current.focus()
}
render(){
return (
<div>
<input ref={this.input}/>
</div>
)
}
}
export default RefSample
input = React.createRef()
<input
ref ={(ref) => this.input=ref}
(...)/>
handleButtonClick = () =>{
this.setState({
clicked:true,
validated:this.state.password ==='0000'
})
this.input.focus()
}
<MyComponent ref={(ref) ⇒{this.myComponent=ref}} />
import React, {Component} from 'react'
class ScrollBox extends Component{
render(){
const style={
border:'1px solid black',
height:'300px',
width:'300px',
overflow:'auto',
position:'relative'
}
const innerStyle={
width:'100%',
height:'650px',
background:'linear-gradient(white,black)'
}
return (
<div
style={style}
ref ={(ref)=>{this.box=ref}}>
<div style={innerStyle}></div>
</div>
)
}
}
export default ScrollBox
<div ref ={(ref)=>{this.box=ref}}>
ref 설정하기
class ScrollBox extends Component{
scrollToBottom = () =>{
const {scrollHeight,clientHeight} = this.box
this.box.scrollTop = scrollHeight - clientHeight
}
render(){...}
/App.js
<ScrollBox ref={(ref)=>this.ScrollBox=ref}/>
<button onClick={()=>this.ScrollBox.scrollToBottom()}>
맨 밑으로
</button>
scrollToBottom
scrollTop
: 세로 스크롤바 위치
scrollHeight
: 스크롤이 있는 박스 안의 div 높이
이렇게 만든 메서드는 부모 컴포넌트에서 ScrollBox에 ref를 달면 사용 가능하다.