React学习笔记案例2
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <style> .myheader{ height: 20px; background-color:blanchedalmond; font-size: 14px; color: blueviolet; padding: 2px; } .mymain{ background-color:cornflowerblue; height: 70px; } </style> <body> <div id="app"></div> </body> <script src="./js/react.js"></script> <script src="./js/react-dom.js"></script> <script src="./js/babel.min.js"></script> <script src="./js/MyHeader.js" type="text/babel"></script> <script src="./js/MyMain.js" type="text/babel"></script> <script src="./js/App.js" type="text/babel"></script> <script type="text/babel"> ReactDOM.render( <App/>, document.getElementById('app') ) ; </script> </html>
App.js代码 var App = React.createClass({ test:function(){ this.setState({sex:'女'}); }, t:function(){ this.setState({name:'陈杜'}); }, getInitialState:function(){ return { title:'体检报告', name:'王晓明', sex:'男', time:2 } }, //componentDidMount 在初始化render之后只执行一次,在这个方法内,可以访问任何组件,componentDidMount()方法中的子组件在父组件之前执行 //从这个函数开始,就可以和 JS 其他框架交互了,例如设置计时 setTimeout 或者 setInterval,或者发起网络请求 componentDidMount:function(){ var t_tmp = 1; this.timer=setInterval(function(){ t_tmp += 1; this.setState({time:t_tmp}); }.bind(this),1000); }, render:function(){ return <div> <MyHeader name={this.state.name} title={this.state.title}/> <MyMain name={this.state.name} sex={this.state.sex} time={this.state.time}/> <buttom onClick={this.t} >测试</buttom> </div> } });
MyHeader代码: var MyHeader = React.createClass({ getDefaultProps:function(){//属性的设置 return { name:'张晓明', title:'的体检报告' } }, render:function(){ return <div className="myheader"> {this.props.name} {this.props.title} </div>; } });
MyMain.js代码 var MyMain = React.createClass({ getDefaultProps:function(){ return{ name:'张晓明', sex:'不男不女', time:1 } }, render:function(){ return <div className="mymain"> 名字:{this.props.name}<br/> 性别:{this.props.sex}<br/> 已经存活了{this.props.time}秒 </div> } });
hardDream!!