React学习笔记
学习React的过程中,领悟到了一些基础要点,决定记录下来,以便以后阅读查看。
组件:
组件类首字母必须大写
1 2 3 4 5 6 7 8 9 10 | var Hello = React.createClass({ render: function(){ return <h1>Hello ,{this.props.name}< / h1> } }) ReactDOM.render( <Hello name = "cxs" / >, document.body ) |
this.props.children
this.props对象属性与组件属性一一对应。this.props.children是例外,它表示组件的所有节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var NotesList = React.createClass({ render: function(){ return ( <ol> { React.children. map (this.props.children, function(child){ return <li>{child}< / li> }) } < / ol> ); } }); ReactDOM.render( <NotesList> <span>Hello< / span> <span>world< / span> < / NotesList>, document.body ); |
PropTypes
组件的属性可以接受任意值。需要一种验证机制,验证别人使用组件时提供的参数是否合法
1 2 3 4 5 6 7 8 | var Title = React.createClass({ propTypes: { title: React.propTypes.string.isRequired, }, render: function(){ return <h1>{this.props.title}< / h1> } }); |
获取真实DOM节点
组件的是virtual DOM。需要获取真实DOM节点时,要用到ref属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var Component = React.createClass({ handleClick: function(){ this.refs.myTextInput.focus(); }, render: function(){ return ( <div> < input type = "text" ref = "myTextInput" / > < input type = "button" value = "Focus the text input" onClick = {this.handleClick}> < / div> ) } }) ReactDOM.render( <Component / >, document.body ) |
this.state
React的状态机,状态的变化可以出发重新渲染UI
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var LikeButton = React.createClass({ getInitialState: function(){ return {liked: false}; }, handleClick: funtion(event){ this.setState({liked: !this.state.liked}); }, render: function(){ var text = this.state.liked ? 'like' : 'dont like' ; return ( <p onclick = {this.handleClick}> < / p> ) } }) ReactDOM.render( <LikeButton / >, document.body ) |
手机阅读请扫描下方二维码:
12345678

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
12345678

12345678
12345678
12345678
12345678
12345678

1

1

1

1

1

1

1

1

1

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1