引用仿照菜鸟教程的例子:
(需要网页有一个id为example333的div)
var HelloMessage = React.createClass({ getDefaultProps(){ return { password: 123456, }; }, render:function(){ return ( <div> <h1>Hello {this.props.name}!</h1> <Time time={this.props.time}/> <Link link={this.props.link}/> <p>password:{this.props.password}</p> </div> ); } }); var Time = React.createClass({ getInitialState:function(){ return {clickCount:0}; }, render:function(){ return (<div><p>Time:</p><h1 onClick={this.handleClick}>click:{this.state.clickCount}---time : {this.props.time}</h1></div>); }, handleClick:function(){ this.setState(function(state){ return {clickCount : state.clickCount+1}; }) } }); var Link = React.createClass({ getInitialState:function () { return {clickCount:0,password:12341234,link:this.props.link}; }, getDefaultProps:function(){ return ({account:'xperia'}); } , render:function(){ return (<div><p>------------------------------</p> <a onClick={this.handleClick} >Link</a><h2>lickClickCount:{this.state.clickCount}</h2> <h3>account...:{this.props.account}</h3><h3>password.....:{this.state.password}</h3> <a href={this.props.link}>传送门</a> <p>-----------------------------------</p></div>); }, handleClick:function () { var clickCount = 111; this.replaceState({clickCount:111,password:11111111}); } }); ReactDOM.render( <HelloMessage name="searlas" time={CurentTime()} link="https://www.baidu.com"/>, document.getElementById('example333') );
初始的效果(没有做样式):
先谈state的部分:
状态是一个可以随意变动的属性。
初始化:在Time类里面初始化的时候赋值了time这个state为当前的时间(使用了一个js获取)。
var Time = React.createClass({ getInitialState:function(){ return {clickCount:0}; }, render:function(){ return (<div><p>Time:</p><h1 onClick={this.handleClick}>click:{this.state.clickCount}---time : {this.props.time}</h1></div>); }, handleClick:function(){ this.setState(function(state){ return {clickCount : state.clickCount+1}; }) } });
更改state:在Time类里面html的部分还有一个click点击事件,即点击<h1>部分的时候,触发this.handleClick
然后执行setState函数,clickCount+1,然后样例会增加1
然后是props部分:
本身初始化的时候可以正常定义props:
getDefaultProps(){ return { password: 123456, }; },
展示也比较正常:
问题是setProps和replaceProps出错:
props相当于本身的属性,好像react不建议修改,使用setProps和replaceProps,在使用过程中好像报错了,那个文档看上去有点问题,去其他博客发现是不建议使用,极客学院里面有梁杰Liangjie:说组件不能修改prop,只能由父类在传入的时候设置。
var HelloMessage = React.createClass({ getDefaultProps(){ return { password: 123456, }; }, render:function(){ return ( <div> <h1 onClick={this.changeProps()}>Hello {this.props.name}!</h1> <Time time={this.props.time}/> <Link link={this.props.link}/> <p>password:{this.props.password}</p> </div> ); }, changeProps(){ this.setProps({password: 1111}); } });
如果在HelloMessage中加入setProps的函数的话
这样就直接报错了。还是不要用setProps和replaceProps了