props는 컴포넌트 외부에서 컴포넌트를 조작하기 위해 사용하는 반면
state는 props 값에 따라 내부 구현에 필요한 데이터!
props의 값을 state로 만들고 그 값을 해당 컴포넌트의 props로 전달이 가능함
constructor 함수를 작성
이 함수는 컴포넌트 실행 시 제일 먼저 실행되어 초기화를 담당함
constructor(props){
super(props);
this.state= {
subject:{title:'WEB', sub:'world wide web!'},
contents:[
{id:1,title:'HTML',desc:'HTML is for information'},
{id:1,title:'abc',desc:'abcdefg'},
{id:1,title:'hello',desc:'hello everyone!'}
]
}
}
컴포넌트에 해당 함수를 작성하여 초기화를 하고, 실제 컴포넌트에서 state 값을 가져와 사용할 떄는 {this.state.subject.title}
과 같은 방식으로 사용함
부모의 state를 바꾸어 데이터를 자동으로 바꾸는 방식도 가능함
Art 컴포넌트에 여러 데이터를 넣고싶은 경우 contents 배열을 생성
<Art data = {this.state.contents}></Art>
컴포넌트 사용할 때 만든 배열을 이름을 주어 할당함
class Art extends Component{
render(){
var lists = [];
var data = this.props.data;
var i =0;
while (i<data.length){
lists.push(<p><h2>{data[i].title}</h2>{data[i].desc}</p>);
i = i+1;
}
return(
<article>
{lists}
</article>
);
}
}
this.props.data;
이름으로 데이터 가져와서 사용한다
리액트에서는 state 값이 바뀌면 그 state를 가지고 있던 컴포넌트의 render 함수가 다시 호출된다!
이를 이용하여 클릭을 하면 화면이 바뀌는 형식의 event 생성 가능
링크를 클릭했을 떄 onClick 이벤트를 사용한다
자바 스크립트에서는 onClick = ""
로 사용하지만 리액트에서는 onClick={}
로 사용하게 된다
a 태그 : URL을 기준으로 링크를 만들어주는 역할을 한다!
만드는 방법
a 태그의 속성으로 onClick을 추가한다
ex) onClick = {function (){}}
render 함수 내에서의 this
: 컴포넌트를 가리킨다!
onClick 메서드 내에서의 this는 기본적으로 undefined임!
따라서 bind 함수를 이용해서 this를 강제 주입해준다!
state의 값들은 constructor 실행 때 this.state로 인해 초기화된다
이후에 state 값을 직접 바꾸게 된다면 리액트가 모르게 값을 바꾸게 되고, 렌더링이 되지 않는다..!
-> setState 함수를 이용하면 렌더링까지 하게 됨!
예시 코드
render(){
var _title, _sub = null;
if(this.state.mode === 'first'){
_title = this.state.first.title;
_sub = this.state.first.sub;
}else if(this.state.mode === 'second'){
_title = this.state.second.title;
_sub = this.state.second.sub;
}
return(
<div className='App'>
<h3><a onClick={function(e){
if(this.state.mode === 'first'){
this.setState({mode : 'second'});
}else{
this.setState({mode : 'first'});
}
}.bind(this)}>
click here!!
</a></h3>
<h4>
{_title}
</h4>
{_sub}
{/* <Clickhere
title = {_title}
sub = {_sub}></Clickhere> */}
</div>
);
}
컴포넌트 내의 a 태그가 클릭되면 어떤 일이 일어나게 하고 싶을때...
컴포넌트의 props으로 onClick시 실행할 함수를 넘겨준다!
<Headline
onEvent = {function (){
alert("hihihi");
}.bind(this)}></Headline>
Headline 컴포넌트의 props로 onEvent라는 함수를 넘겨줌
<header>
<h2><a onClick={function(e){
e.preventDefault();
this.props.onEvent();
}.bind(this)}>
My react Page!
</a>
</h2>
hello everyone!
</header>
header 함수 a태그 onClick함수에서 this.props.onEvent();
방식으로 함수 호출해서 사용이 가능하다!
e.preventDefault();
는 링크를 클릭했을 떄 페이지가 바뀌는 것을 막아준다..!