'React'에 해당되는 글 1건

  1. 2018.04.15 pure compoennet, ref등

pure compoennet, ref등

React.js 2018. 4. 15. 21:56

<주요키워드>

className : 리액트에선 class가 아니라 className으로 써야 한다. css도 적용될 듯.

props   : extends Component엔 자동으로 들어오고,   Functional Component는 선언시 꼭 인풋으로 선언한다.

this.state  :   this.setState로  state변수를 바꿔야 하며 이 setState함수를 통해 redraw(=Update)가 발생한다. 
                    처음 그릴땐 Mount라 부르고, 그 이후부터는 Update라 부른다.




<Unique ID>

react에서 <ul>과 같은 list들에선  일반적으로 unique한 ID가 필요하다. (향후 선택을 위해서..)

array 데이타를 ul안에서 사용할 경우 array의 index를 사용해도 된다.

데이타 세팅시에는 UniqueId를 많이 사용한다.  

 

import UniqueId from 'react-html-id';

class App extends Component {

constructor() {
super();
UniqueId.enableUniqueIds(this);

this.state = { //uniqueID를 쓰려면 this때문에 생성자에서?
users: [
{id:this.nextUniqueId(), name:'Kim', age:10},
{id:this.nextUniqueId(), name:'Lee', age:20}
]
}
//array.findIndex( )로 true리턴해서 쉽게 찾을수 있음.
}
render() {
return (
<div className="App">
<ul>
{
this.state.users.map((user,index) => {
return (<User age={user.age} id={user.id} index={index}>{user.name}</User>)
})
}
</ul>
</div>
);
}
}




<Router>  REF , youtube


react에선 java-spring의 controller처럼 url을 관리해주는 메커니즘이 router이다.

url을 파라미터로 받을 수도 있다.

Link, NavLink, Redirect, Prompt도 유사하다.


   dependeny 필요: react-router-dom


   props:   exact : 정확한 매치만 허용,  strict:마지막 슬래쉬 까지도 정확히 체크


   match:  마치 props를 사용하듯이, Router에서는 match를 사용해  파라미터를 받아서 사용할 수 있다.

     => const User = ({match})  => {}  에서  match.params.myVar 사용가능  (props와는 달리 {match}중괄호 필요)

     =>      <Route path="/user;:myVar"  component={User} /> 이렇게 선언해 놓아야 함.

    

      match.url도 이용가능.



<Fragment>

  div를 2개써야 한다던지 할때 그 외부를  또 div로 싸도 되긴 하지만

 일부러 이렇게 div를 넣지 않아도 되게, react에서 특별히 제공하는 태그이다.

 실제 렌더링 되지는 않고, 2개를 가상으로 묶어주기만 한다.




<pure component>    REF

일반적으로 Component를 상속해서 Mount와 Update가 발생하지만,

PureComponent를 상속하면 Mount만 발생한다. 

아주 간단한 .. 한번 만들면 update할 일이 없는 component는 PureComponent를 쓰는게 좋다.

- 하지만 조심할 필요는 있다.    




<ref>  REF : (onKeyUp 코드도 같이 있음.)

ref={(input) => { this.firstName = input; }}

를 정의하면 ${this.firstName.value}로 사용가능하다.

외부에서 App.firstName도 사용가능하다.


16.3.0 부터는 (생성자등에서) productNameRef = React.createRef(); 지원. 조금더 간단함.



<Type Check>    REF

(개인적으로는 아직, typeCheck가 많이 필요한지 필요성을 못 느끼고 있다.

백엔드를 다른 language로 하기 때문에 필요성을 못 느낀 걸 수도 있는데..

아래와 같이 3가지 type check가 존재하는 걸 보면 분명 필요성 있는 곳이 있는것 같다..)


1. 일반적으로 간단한 type check는 PropType으로 한다. 

2. 좀 더 복잡한 type check는   react-flow  (yarn을 이용한 설치)를 이용하며

3. 가장 복잡하면서 확실한 type check는 typeScript를 이용한다..확장자도 tsx로 바뀌는 만큼 무겁다.. 




Posted by yongary
,