props
props属性用于沟通组件
在一种很简单的场景下,可以通过父组件向子组件传递数据,当然在 组件类 中你也可以设置默认的props属性。
且让我们看一看一个非常简单的例子:
99 这样的数据是从外部传入的,为了能够正确的显示它,你可以采用两种方式:
- 显示的传入你的props数据
- 使用spread attributes的方式传入数据
import classNames from 'classnames';
function Selector (props){
const { type , count } = props;
if (!type) {
return null;
}
const css = classNames({
['remind-'+ type ]: type
});
return (
<span
className={ css }
>
{ count }
</span>
);
}
export default Selector;
在Footer的render中显示的传入:
<Selector type={ type } count={ count }/>
在Footer的render中spread attributes:
<Selector
{...this.props}
/>
有时候明显你应该选择显示的方式(good),这样你可以很显明的知晓数据流动的方向。
Prop Validation
在进行传递之前,你可以对props数据进行类型的验证,这在大型Web应用中非常的有用,在实现Footer中外部传入的是一个items数组,你可以使用PropTypes去验证传入数据的类型。
const propTypes = {
items: PropTypes.array
};
const defaultProps = {
items: []
};
Footer .... // class
Footer.propTypes = propTypes;
更多有帮助的信息可访问:Prop Validation
组件设置默认的Prop
在某些情况下,我们还需要对组件类设置默认的Props数据,比如我们在实现Button按钮时需要设置tag默认为button。
const defaultProps = {
size: 'normal', // full small
type: 'btn',
disabled: false,
tag: 'button'
};
在ES2105中使用defaultProps
来表示默认设置的props
Button.defaultProps = defaultProps;
提个额外的话题
相信很多朋友在看别人的代码时,会出现如下的代码:
const { type, children, ...other} = this.props;
这属于ES7草案。