1.propTypes
子组件规定父组件传过来的值的类型 注意下面注释的地方
import React, { Component } from 'react';
import PropTypes from 'prop-types' // PropTypes 首字母大写
class Child extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return (
<div>
child
{this.props.test}
</div>
);
}
}
// 这个propTypes 是驼峰
Child.propTypes = {
// 这个PropTypes 首字母大写
test: PropTypes.string
}
export default Child;
2. defaultProps
规定父组件传过来的默认值,如果父组件不传这个值,子组件会使用这个默认值
子组件:
import React, { Component } from 'react';
class Child extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return (
<div>
child
{/* 默认值 sss */}
{ this.props.testname}
</div>
);
}
}
Child.defaultProps = {
testname:'sssss'
}
export default Child;
父组件:
import React, { Component } from 'react';
import Child from './Child'
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
pdata:'父数据'
}
}
render() {
return (
<div>
{/* 父组件没有传testname */}
<Child></Child>
</div>
);
}
}
export default Parent;