21.01.20

민주·2021년 1월 20일
0

[REF]

- React native에는 selector개념이 없기 때문에 특정요소를 불러올 때 ref를 사용한다.
- Ref를 활용하면 DOM에 직접 접근 할 수 있다.
- object처럼 특정한 속성을 추가하여 사용 할 수도 있다.
export default function RefDom(){

    const myRef = React.useRef();

    const [val,setVal] = React.useState('내용을 입력하세요');

    const txtFocus = ()=>{
        //버튼을 누르면 INPUT박스 안의 내용이 모두 사라지도록
        setVal('');
        console.log(myRef);
        myRef.current.focus();
    }

    return(
        <View>
            <TextInput ref={myRef} //ref사용할곳에 선언
            style={{height:40, margin:10, 
            borderColor:'gray',borderWidth:1}}
            onChangeText={(val)=>{setVal(val)}} value={val}   
        />
            <Button title="TAB" onPress={()=>{txtFocus()}}/>
        </View>
    )
}
- React.을 사용하면 react로 부터 import되는 함수들은 import문이 따로 필요가없다.
- console.log(myRef) : myRef로 어떤 함수를 쓸수있는지 확인가능
- myRef.current.focus : ref선언한곳에 focus
- useRef하면 영역이 생기게 되고 안에 태그 요소와 속성을 추가 할 수 있다.
- useRef는 랜더링상황에 연관받지 않으므로 값의 변화에도UI에는 영향을 미치지 못한다.

[component]

- React 는 Component 단위로 UI 나 기능이 구현 된다.
- Component 선언 방법은 크게 class 선언과 function 선언이 있다.
- 함수형 : 클래스에서 state를 하는 역할->useState()
- 클래스 형 : state를 통해 어떤 값에 변화를 줄수 있었다.
class ClassComp extends Component{
    constructor(props){
        super(props);
        this.state = {count:0};
    }
    //render밖에서 일어남
    setCount(){
        this.setState({count:this.state.count+1});
    };
    //rendering밖에있어서 인지가능, alert은 render와 상관 없는애다
    alertCount(){
        setTimeout(()=>{
            alert('You Clicked ON : '+this.state.count);
        },3000)
    };

    render(){
        return(
            <View style={{flex:1,flexDirection:'column',
            justifyContent:'center'}}>
                <Text>You Click {this.state.count} times</Text>
                <View style={{margin:5}}>
                    <Button title="click me" 
                    onPress={()=>{this.setCount()}}/>
                </View>
                <View style={{margin:5}}>
                    <Button title="Show Alert" 
                    onPress={()=>{this.alertCount()}}/>
                </View>
            </View>
        );
    }
}
export default ClassComp;
- 클래스형 컴포넌트
- 클래스형 컴포넌트는 render()함수가 따로 존재하기 때문에 alert을 
  사용할때 rendering밖에있어서 인지가능하다.
- alert은 render와 상관 없는애다.
export default function FuncComp(){
    
    const [count,setCount] = React.useState(0);
    const refVal = React.useRef(0);

    const alertCount= ()=>{
        setTimeout(()=>{
            alert('you clicked ON : ' + refVal.current);
        },3000)
    };
    const updateCount= (cnt)=>{//count+1을 cnt로 받아옴
        setCount(cnt)
        //ref는 render와 관계없이 값을 유지 시킨다
        refVal.current = cnt; 
    }

    return(
        <View style={{flex:1,flexDirection:'column',
        justifyContent:'center'}}>
            <Text>You Click {count} times</Text>
            <View style={{margin:5}}>
                <Button title="click me" 
                onPress={()=>{updateCount(count+1)}}/>
            </View>
            <View style={{margin:5}}>
                <Button title="Show Alert" 
                onPress={()=>{alertCount()}}/>
            </View>
        </View>
    );
}
- 함수형 컴포넌트에서는 모든일이 render()안에서 일어나기 때문에 alert는 
render랑 상관없는애여서 제대로 인식을 못한다.
- 그래서 render와 상관없이 alert을 해주려면 ref를 사용한다.

[useEffect]

 useEffect(()=>{
    //컴포넌트가 렌더링 하면 무조건 호출된다
    console.log('component Did Mount!');
 });*/
- componentDidMount : 컴포넌트가 실행 되었을 때
- 클래스 컴포넌트에서는 componentDidMount자체로 사용하면 된다.
  useEffect(()=>{
  	//[]안의 state가 변경되면 실행
    console.log('component Did Mount!');
  },[num]);
- componentDidUpdate : 컴포넌트 내에 특정 state가 변화가 생겼을 때
- []안에 아무것도 넣지 않으면 실행이 안된다
- 클래스 컴포넌트에서는 componentDidUpdate자체로 사용하면 된다.
useEffect(()=>{
    console.log('component Did Mount!');//1.컴포넌트 마운트
    return () =>{
      console.log('이전 컴포넌트 제거');//0.이전 컴포넌트가 사라 질 때 실행
    }
  },[num]);
- componentWillUnMount : 컴포넌트가 수명을 다하고 사라질 때

[Component API]

- Activity Indicator : 로딩이미지
- FlatList : 특정 데이터를 가져와 HTML의 ul과 li 처럼 보여지게 만든다.
- Touchable : 좀 더 자유로운 표현이 가능한 버튼
profile
개발이좋아요

0개의 댓글