반응형

props 는 컴포넌트에서 사용할 데이터중 변하지 않는 데이터를 다룰때 사용한다. 


Parent 컴포넌트에서 child 컴포넌트로 데이터를 전달할 때 props를 사용한다. 


컴포넌트의 render() 메소드 내부에 {this.props.propsName} 형태로 넣고 컴포넌트에서 사용할 때에는 <> 안에 propsName='value' 형태로 값을 설정 한다. 


- render() 메소드 내부


1
2
3
4
5
6
7
8
9
10
11
12
13
class App extends React.Component {
    render(){
 
        let text = "Hello HI";
 
        return (
            <div>
                <Header title={this.props.headerTitle}/>
                <Content title={this.props.contentTitle} body={this.props.contentBody}/>
            </div>
        );
    }
}
cs


- 컴포넌트


1
2
3
4
ReactDOM.render(<App headerTitle="Welcome"
                    contentTitle="Stranger"
                    contentBody="welcome to ex App"/>
                    , rootElement);
cs



- Default 값 사용시에는 App 내부에 className.defaultProps={propsName:value} 로 설정해주면 된다. 


1
2
3
4
5
6
App.defaultProps={
    headerTitle:'Default header',
    contentTitle: 'Default contentTitle',
    contentBody: 'Default contentBody'
};
 
cs


- propType 지정


1
2
3
4
Content.propType={
    title: React.PropTypes.string,
    body: React.PropTypes.string.isRequired
};
cs


title 과 body 를 모두 string으로 지정하고 body 는 필수로 설정한다. 필수 지정일경우 값이 없으면 오류가 난다.




<이 문서에 작성된 소스는 https://velopert.com 에 게시된 소스 입니다. >


----------------------------------------------------------------------------------------------------------------


추가.


React 에서는 단방향 흐름을 강조하는 것 같다. 그래서 props는 상위 컴포넌트에서 하위 컴포넌트로 전달되는 데이터이며, 또한 이것을 하위 컴포넌트에서 변경되는것은 권장하지 않는것 같다...



728x90
반응형

'Development > Frontend skills' 카테고리의 다른 글

npm install --save --save-dev  (0) 2017.05.30
map() 메소드 사용  (0) 2017.01.16
React.. 끄적끄적.  (0) 2017.01.09
Mac 에서 Node.js 설치  (0) 2017.01.05
jquery radio button 속성 설정  (0) 2013.09.04

+ Recent posts