Typechecking With PropTypes
Note: React.PropTypes
is deprecated as of React v15.5. Please use the prop-types
library instead.
As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don't use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special propTypes
property:
import PropTypes from 'prop-types'; class Greeting extends React.Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } Greeting.propTypes = { name: PropTypes.string };
PropTypes
exports a range of validators that can be used to make sure the data you receive is valid. In this example, we're using PropTypes.string
. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. For performance reasons, propTypes
is only checked in development mode.
1.将父组件参数全部传递给子组件的快捷方法:
{...this.props}
2.设置默认prop值
step-1 使用ES6语法定义变量defaultProps
const defaultProps={ username:'sunny' //当父组件没有设置对应参数时,会显示该内容,若设置了,设置参数会覆盖自定义默认参数 }
step-2 为所在组件的参数设置默认值
BodyIndex.defaultProps=defaultProps
PS:含props的属性,获取或传递的,都是来自父组件的参数值
Default Prop Values--》defaultProps属性
You can define default values for your props
by assigning to the special defaultProps
property:
class Greeting extends React.Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } // Specifies the default values for props: Greeting.defaultProps = { name: 'Stranger' }; // Renders "Hello, Stranger": ReactDOM.render( <Greeting />, document.getElementById('example') );
The defaultProps
will be used to ensure that this.props.name
will have a value if it was not specified by the parent component. The propTypes
typechecking happens after defaultProps
are resolved, so typechecking will also apply to the defaultProps
.