淺談React的類型檢測-PropTypes

隨著應(yīng)用的日益變大标捺,保證組件的正確使用顯得日益重要芳悲,為此引入React.propTypes:react.PropTypes 提供很多驗證器來驗證傳入數(shù)據(jù)的有效性,當(dāng)向props傳入無效數(shù)據(jù)時,JavaScript 控制臺會拋出警告掷邦。

注意為了性能考慮,只在開發(fā)環(huán)境驗證 propTypes椭赋。

一抚岗、聲明props為指定的js基本類型,可傳可不傳哪怔。

1宣蔚、React.PropTypes.array

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        name: React.PropTypes.array.isRequired    
    },    
    render: function() {    
        return (    
            <div>{this.props.name}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox name={["Alice", 30, true]} />,    
    document.getElementById('timeBox')    
);  
2、React.PropTypes.bool

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        student: React.PropTypes.bool.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.student ? "Hello, react!" : "Sorry!"}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox student={true}  />,    
    document.getElementById('timeBox')    
); 

注意:<div>{this.props.student}</div> 渲染不出包含true的div认境?胚委??

3叉信、React.PropTypes.func

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        sayHello: React.PropTypes.func.isRequired    
    },    
    render: function() {  
        this.props.sayHello();  
        return (    
            <div>Hello, react!</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox sayHello={function sayHello() {console.log("Hello, react!");}}  />,    
    document.getElementById('timeBox')    
);   
4亩冬、React.PropTypes.number

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        age: React.PropTypes.number.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.age}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox age={23}  />,    
    document.getElementById('timeBox')    
);   
5、React.PropTypes.object

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        family: React.PropTypes.object.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.family.mother} & {this.props.family.father}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox family={{mother: "Alice", father: "Bruce"}} />,    
    document.getElementById('timeBox')    
);   
6硼身、React.PropTypes.string

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        name: React.PropTypes.string.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.name}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox name="Alice" />,    
    document.getElementById('timeBox')    
);   
7硅急、React.PropTypes.symbol
var MyBox = React.createClass({      
    propTypes: {      
        name: React.PropTypes.symbol.isRequired      
    },      
    render: function() {  
        var obj = {  
            [this.props.name]: "Alice"  
        }  
        return (      
            <div>{obj[this.props.name]}</div>      
        );      
    }      
});      
ReactDOM.render(      
    <MyBox name={Symbol()} />,      
    document.getElementById('timeBox')      
);   

二、聲明props為數(shù)字佳遂、字符串铜秆、DOM 元素或包含這些類型的數(shù)組或fragment。

React.PropTypes.node

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        children: React.PropTypes.node.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.children}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox>  
        [<span>Hello, react!</span>, 30, "Alice"]  
    </MyBox>,    
    document.getElementById('timeBox')    
);   

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        children: React.PropTypes.node.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.children}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox>  
        {true}  
    </MyBox>,    
    document.getElementById('timeBox')    
);   

三讶迁、聲明props為React元素(原生HTML元素或React類)

React.PropTypes.element

正確示范:

var MyBox = React.createClass({    
    propTypes: {    
        children: React.PropTypes.element.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.children}</div>    
        );    
    }    
});    
var Children = React.createClass({    
    render: function() {  
        return (    
            <span>Hello</span>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox>  
        <div>  
            <Children />  
            <span> React</span>  
        </div>  
    </MyBox>,    
    document.getElementById('timeBox')    
);   

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        children: React.PropTypes.element.isRequired    
    },    
    render: function() {  
        return (    
            <div>{this.props.children}</div>    
        );    
    }    
});    
var Children = React.createClass({    
    render: function() {  
        return (    
            <span>Hello</span>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox>  
        <Children />  
        <span> React</span>  
    </MyBox>,    
    document.getElementById('timeBox')    
);   

四连茧、聲明props為某個指定的類

React.PropTypes.instanceOf(MyBox)

var MyBox = React.createClass({      
    propTypes: {      
        children: React.PropTypes.instanceOf(Array)     
    },      
    render: function() {  
        return (      
            <div>{this.props.children}</div>      
        );      
    }      
});        
ReactDOM.render(      
    <MyBox>  
        {[1, 2, 3]}  
    </MyBox>,      
    document.getElementById('timeBox')      
);   

注意:指定的類不能是自定義的React類

五、聲明props為某些指定值中的一個(用enum的方式)

React.PropTypes.oneOf(['Alice', 'Bruce'])

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        name: React.PropTypes.oneOf(['Alice', 'Bruce'])    
    },    
    render: function() {  
        return (    
            <div>{this.props.name}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox name="Cindy" />,    
    document.getElementById('timeBox')    
);  

六巍糯、聲明props為某些類型中的一個

React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, ...])

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        prop: React.PropTypes.oneOfType([  
            React.PropTypes.string,  
            React.PropTypes.number  
        ])   
    },    
    render: function() {  
        return (    
            <div>{this.props.prop}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox prop={true} />,    
    document.getElementById('timeBox')    
);  

七啸驯、聲明props為指定類型組成的數(shù)組

React.PropTypes.arrayOf(React.PropTypes.number)

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        prop: React.PropTypes.arrayOf(React.PropTypes.number)  
    },  
    render: function() {  
        return (    
            <div>{this.props.prop}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox prop={["Alice", 23, true]} />,    
    document.getElementById('timeBox')    
);  

八、聲明props為指定類型的屬性構(gòu)成的對象

React.PropTypes.objectOf(React.PropTypes.number)

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        family: React.PropTypes.objectOf(React.PropTypes.string)    
    },    
    render: function() {  
        return (    
            <div>{this.props.family.mother} & {this.props.family.father}</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox family={{mother: "Alice", age: 23}} />,    
    document.getElementById('timeBox')    
);  

九祟峦、聲明props為特定形狀參數(shù)的對象

React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
})

十罚斗、聲明props為必須的某類型

React.PropTypes.*.isRequired

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        name: React.PropTypes.string.isRequired    
    },    
    render: function() {  
        return (    
            <div>Hello, react!</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox />,    
    document.getElementById('timeBox')    
);   

十一、聲明props為必須的任意類型

React.PropTypes.any.isRequired

錯誤示范:

var MyBox = React.createClass({    
    propTypes: {    
        name: React.PropTypes.any.isRequired    
    },    
    render: function() {  
        return (    
            <div>Hello, react!</div>    
        );    
    }    
});    
ReactDOM.render(    
    <MyBox />,    
    document.getElementById('timeBox')    
);   

參考:http://blog.csdn.net/zhouziyu2011/article/details/70842310

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宅楞,一起剝皮案震驚了整個濱河市针姿,隨后出現(xiàn)的幾起案子袱吆,更是在濱河造成了極大的恐慌,老刑警劉巖距淫,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绞绒,死亡現(xiàn)場離奇詭異,居然都是意外死亡榕暇,警方通過查閱死者的電腦和手機蓬衡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來彤枢,“玉大人狰晚,你說我怎么就攤上這事〗煞龋” “怎么了壁晒?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長业栅。 經(jīng)常有香客問我秒咐,道長,這世上最難降的妖魔是什么式镐? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮固蚤,結(jié)果婚禮上娘汞,老公的妹妹穿的比我還像新娘。我一直安慰自己夕玩,他們只是感情好你弦,可當(dāng)我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著燎孟,像睡著了一般禽作。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上揩页,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天旷偿,我揣著相機與錄音,去河邊找鬼爆侣。 笑死萍程,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的兔仰。 我是一名探鬼主播茫负,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼乎赴!你這毒婦竟也來了忍法?” 一聲冷哼從身側(cè)響起潮尝,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎饿序,沒想到半個月后勉失,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡嗤堰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年戴质,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片踢匣。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡告匠,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出离唬,到底是詐尸還是另有隱情后专,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布输莺,位于F島的核電站戚哎,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏嫂用。R本人自食惡果不足惜型凳,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嘱函。 院中可真熱鬧甘畅,春花似錦、人聲如沸往弓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽函似。三九已至槐脏,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間撇寞,已是汗流浹背顿天。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蔑担,地道東北人露氮。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像钟沛,于是被迫代替她去往敵國和親畔规。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 以下內(nèi)容是我在學(xué)習(xí)和研究React時恨统,對React的特性叁扫、重點和注意事項的提取三妈、精練和總結(jié),可以做為React特性...
    科研者閱讀 8,232評論 2 21
  • 原教程內(nèi)容詳見精益 React 學(xué)習(xí)指南莫绣,這只是我在學(xué)習(xí)過程中的一些閱讀筆記畴蒲,個人覺得該教程講解深入淺出,比目前大...
    leonaxiong閱讀 2,835評論 1 18
  • 自己最近的項目是基于react的对室,于是讀了一遍react的文檔模燥,做了一些記錄(除了REFERENCE部分還沒開始讀...
    潘逸飛閱讀 3,385評論 1 10
  • 深入JSX date:20170412筆記原文其實JSX是React.createElement(componen...
    gaoer1938閱讀 8,065評論 2 35
  • React Native是基于React的,在開發(fā)React Native過程中少不了的需要用到React方面的知...
    亓凡閱讀 1,472評論 1 4