>React屬性驗證器
這個與react的版本有關系
類型 | 驗證器
---|:--
數組 | React.PropTypes.array
布爾值 | React.PropTypes.bool
函數 | React.PropTypes.func
數字 | React.PropTypes.number
對象 | React.PropTypes.object
字符串 | React.PropTypes.string
## 函數定義/類定義組件
### 1.無狀態函數式組件
定義一個組件最簡單的方式是使用JavaScript函數:
官方例子:
~~~javascript
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
~~~
非官方例子
~~~JavaScript
const Summary = ({ ingredients, steps, title })=>{
return <div>
<h1>{ title }</h1>
<p>{ ingredients } Ingredients | { steps } Steps</p>
</div>
}
Summary.propTypes = {
ingredients: React.Proptypes.number.isrequired,
steps: React.Proptypes.number.inRequired
}
Summary.defaultProps = {
ingredients: 1,
steps: 1
}
~~~
或者直接在參數中直接設置默認屬性和值
~~~javascript
const Summary = ({ ingredients = 0, steps = 0,title = '[recipe]' }) => {
return <div>
<h1>{ title }</h1>
<p>{ ingredients } Ingredients | { steps } Steps</p>
</div>
}
~~~
該函數是一個有效的React組件,它接收一個單一的“props”對象并返回了一個React元素。我們之所以稱這種類型的組件為函數定義組件,是因為從字面上來看,它就是一個JavaScript函數。
### 2.ES5/ES6類
我們先看看ES5的寫法:
ES5寫法如下:
~~~javascript
const Summary = createClass({
propTypes = {
ingredients: PropTypes.number,
steps: PropTypes.number,
title: PropTypes.string
}
getDefaultProps() {
return {
ingredient: 0,
steps: 0,
title: "[recipe]"
}
}
render() {
const { ingredients, steps, title } = this.props
return (
<div>
<h1>{ title }</h1>
<p>{ ingredients } Ingredients | { steps } Steps</p>
</div>
)
}
})
~~~
你也可以使用 [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) 來定義一個組件:
官方例子
~~~javascript
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
~~~
非官方例子
~~~javascript
class Summary extends React.Component {
render () {
const { ingredients, steps, title } = this.props
return (
<div>
<h1>{ title }</h1>
<p>{ ingredients } Ingredients | { steps } Steps</p>
</div>
)
}
}
Summary.propTypes = {
ingredients: Proptypes.number,
steps: Proptypes.number,
// 自定義屬性 title
title: (props, propName) => {
(typeof props[propName] !== 'string') ?
new Error("A title must be a string") :
(props[propName].length > 20) ?
new Error(`title is over 20 characters`) : null
}
}
Summary.defaultProps = {
ingredients: 0,
steps: 0,
title: "[recipe]"
}
~~~
上面兩個組件在React中是相同的。
>類的靜態屬性
>>類的靜態屬性允許用戶在類的內部聲明中封裝propTypes和defaultProps屬性。屬性構造器也提供了封裝功能和更簡潔的語法:
在類的外部定義屬性 defaultProps和propTypes
最新的ECMAScript 規范提案中提供了一種替代性的解決方案:Class Field & Static Properties
- React進階
- React進階-組件 & Props
- React進階-組件 & Props - 代碼篇
- 組件擴展-組件生命周期
- 組件擴展-組件生命周期-代碼篇
- React-Redux
- Redux入門教程-基本用法
- Redux入門教程-基本用法-代碼篇
- Redux入門教程-中間件和異步操作
- Redux入門教程-React-Redux 的用法
- Redux入門教程-React-Redux的用法-代碼篇
- ES6-變量的解構賦值
- 數組的解構賦值
- 對象的解構賦值
- React用法
- JSX技巧
- ES6-神奇的...
- yarn+webpack+react零基礎創建項目
- 0-init
- 1-webpack.config.md
- 2-react相關依賴
- 3.編寫react相關代碼
- pnpx-react-config
- pnpx+create-react
- pnpm+react-config
- pnpm+react-antd