react props and set the default data type props

To react in the parent component subassembly props pass property values, in order to ensure subassembly props errors due to not an error, it is necessary to set some initialization props.

Use prop-typesset props type

Example code:

import React, {Component} from 'react';
import PropTypes from 'prop-types';

const defaultProps = {
	name: '',
	age: 0,
	sex: '未知',
	list: []
};

class Test extends Component {
	// ...
}

Test.defaultProps = defaultProps;	// 设置默认props
// 设置props参数类型
Test.propTypes = {
	name: PropTypes.string,
	age: PropTypes.number,
	sex: PropTypes.string,
	list: PropTypes.array
};

export default Test;

Prop-types of data types that can be detected

	optionalArray: PropTypes.array,
	optionalBool: PropTypes.bool,
	optionalFunc: PropTypes.func,
	optionalNumber: PropTypes.number,
	optionalObject: PropTypes.object,
	optionalString: PropTypes.string,
	optionalSymbol: PropTypes.symbol,

Guess you like

Origin blog.csdn.net/wang19970228/article/details/95236345