版权声明:未经允许,不可以转载哦~ https://blog.csdn.net/qq_39242027/article/details/83619273
super
Es6中的super可以用在类的继承中,super关键字,它指代父类的实例(即父类的this对象)
子类必须在constructor方法中调用super方法,否则新建实例时会报错。
这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。
不调用super方法,子类就得不到this对象。
constructor(props){
super(props);//用于父子组件传值 用在构造函数中,必须在使用this之前调用
this.state={
name:‘小豆花儿’
}
}
父组件给子组件传值
1.父组件调用子组件时指定属性
传值 title={this.state.title}
传方法 run={this.run}
传整个父组件 home={this}
<PageHeader title={this.state.title} run={this.run} home={this}></PageHeader>
2.子组件使用时
{this.props.title}
—接收值
{this.props.home.run}
—接收方法
{this.props.home}
—接收整个父组件
<h2>{this.props.title}</h2>
<button onClick={this.props.run}>调用父组件的run方法</button><br/><br/>
<button onClick={this.props.home.getData}>获取父组件getData方法</button><br/><br/>
父组件调用子组件的数据和方法
1、调用子组件的时候指定 ref 的值
<Header ref='header'></Header>
2、通过 this.refs.header 获取整个子组件实例 (dom加载完成以后获取)
getHeader=()=>{
alert(this.refs.header.state.msg)
this.refs.header.run()
}
defaultProps:父组件调用子组件不给子组件传值,可以在子组件中使用
父组件调用子组件不传值
<PageHeader></PageHeader>
子组件使用defaultProps
PageHeader.defaultProps={
title:'标题'
}
propTypes:定义父组件给子组件传值的类型
父组件调用子组件
<PageHeader num={111}></PageHeader>
子组件先引入
import PropTypes from 'prop-types';
子组件使用(注意propTypes的大小写)
PageHeader.propTypes={
num:PropTypes.number
}