React Native

ref 사용법

Machine_웅 2020. 6. 24. 17:31
728x90
반응형

ref 사용법

class AutoFocusText extends React.Component{ 
	constructor(props){ 
    	this.textRef = React.createRef() 
    } 
    componentDidMount(){ 
    	console.log(this.textRef.current.state) 
        this.textRef.current.focusTextInput() 
    } 
    render(){ 
    	return( 
        	<CustomTextInput ref={this.textRef}/> 
        ) 
   } 
}

부모클래스에서 자식클래스의 함수를 호출하기

-커스텀 컴포넌트의 ref는 해당 컴포넌트의 인스턴스를 가르킨다
-인스턴스 이므로 모든 데이터와 함수를 가져올수 있다

class CustomTextInput extends React.Component { 
	constructor(props) { 
    	this.inputRef = React.createRef() 
    } 
    
    focusTextInput = () => { 
    	this.inputRef.current.focus() 
    } 
    render() { 
    	return (<input type="text" ref={this.inputRef} />) 
    } 
}

 

728x90
반응형