#react中的constructor()是一个构造方法,用来接收参数
这是ES6对类的默认方法,通过 new
命令生成对象实例时自动调用该方法。并且,该方法是类中必须有的,如果没有显示定义,则会默认添加空的constructor( )
方法
举个简单例子
关于继承(extends):ES5中构造js函数没有继承的写法,通过prototype
达到目的。
//构造函数People function People (name,age){ this.name = name; this.age = age } People.prototype.sayName = function(){ return '我的名字是:'+this.name; } //创建新的子类p1 let p1 = new People('harrisking',23);
ES6中用class构造函数,等价上面的函数
class People{ //构造方法constructor就等于上面的构造函数People constructor(name,age){ this.name = name; this.age = age; } sayName(){ return '我的名字是:'+this.name; } } //创建新的子类p1 let p1 = new People('harrisking',23);
#super() ——继承
定义子类har ,继承父类People,想使用父类的参数,则必须用super()
子类如果没有 constructor
方法,该方法会被默认添加,即任何的子类都有 constructor
方法,无论定义没定义,它就在那里,不离不弃。
在子类的构造函数 constructor( )
中,只有调用 super( )
方法之后,才可以使用 this
关键字,否则会报错。
子类是没有自己的 this
对象的,它只能继承自父类的 this
对象,然后对其进行加工,而super( )
就是将父类中的this对象继承给子类的。没有 super
,子类就得不到 this
对象
class People{ constructor(name,age){ this.name = name; this.age = age; } sayName(){ return '我的名字是:'+this.name; } } class har extends People{ constructor(name,age,sex){ super(name,age);//调用父类的constructor(name,age) this.sex = sex; } haha(){ return this.sex + ' ' + super.sayName();//调用父类的sayName() } }
super()跟super(props)
super()
和super(props)
的区别就是你是否需要在构造函数内使用this.props,如果需要那么你就必须要写props
,如果不需要,那么写不写效果是一样
#代码报错
constructor() { super(); this.state = {c: this.props.count}; }
#代码正常
constructor(props) { super(props); this.state = {c: this.props.count}; }
#数据,或者参数传递:组件的数据存储在props
和state
中
props对组件标签中的标签属性和子节点构成的集合,也
可以理解为从外部传入内部的参数
如何在应用中组合使用 state 和 props,我们可以在父组件中设置 state, 并通过在子组件上使用 props 将其传递到子组件上。
class WebSite extends React.Component { constructor() { super(); this.state = { name: "菜鸟教程", site: "https://www.runoob.com" } } render() { return ( <div> <Name name={this.state.name} /> <Link site={this.state.site} /> </div> ); } } class Name extends React.Component { render() { return ( <h1>{this.props.name}</h1> ); } } class Link extends React.Component { render() { return ( <a href={this.props.site}> {this.props.site} </a> ); } } ReactDOM.render( <WebSite />, document.getElementById('example') );
上面的<name><link>都是WebSite 的子组件,通过
<Name name={this.state.name} />
<Link site={this.state.site} />