propTypes
我们也可以随意为每一个属性指定类型。这对于我们检查和处理属性的意外赋值非常有用。如下面的dropdown,我们指定只有数组才能放入配置。
varNavigation=React.createClass({
getInitialState:function(){
return{
openDropdown:-1
};
},propTypes:{
config:React.PropTypes.array
},document.body);
mixins
我们也可以在组件中加入 mixins。这是一个独立于 React 的基本组件(只是一个对象类型的配置)。这意味着,如果我们有两个功能类似的组件,就可以共享一个配置了(如果初始状态相同)。我们可以抽象化地在 mixin 中建立一个方法,这样就不用把相同的代码写上两次了。
varExampleMixin={
componentDidMount:function(){
},componentWillUnmount:function(){
}
};
varExampleComponent=React.createClass({
mixins:[ExampleMixin],render:function(){
return(
<div>
HelloWorld!
</div>
);
}
});
varAnotherComponent=React.createClass({
mixins:[ExampleMixin],render:function(){
return(
<div>
HelloWorld!
</div>
);
}
});
这样全部组件都有一样的 componentDidMount 和 componentWillUnmount 方法了,保存我们重写的代码。无论如何,你不能 override(覆盖)这些属性,如果这个属性是在mixin里设置的,它在这个组件中是不可覆盖的。