react-learning-001

react

javascript 是一种弱类型的语言 意味着可以修改变量值的数据类型。比如可以定义某个变量为字符串类型,然后将它的值改为数组。并不会对此类操作有任何异议,因此低效管理数据类型会导致花费大量时间在调试应用程序上。

react 为变量类型设置了自动属性验证的机制

类型 验证器
数组 React.PropTypes.array
布尔值 React.PropTypes.bool
函数 React.PropTypes.func
数字 React.PropTypes.number
对象 React.PropTypes.object
字符串 React.PropTypes.string

为组件提供三种属性 标题 食材成分数组 烹饪步骤数组

需要对属性进行验证 确保类型是正确的 无法通过属性验证时,提供默认参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const summary = createClass({
displayName: "Summary",
propTypes: {
ingredients: PropTypes.array.isRequired,
steps: PropTypes.array.isRequired,
title: (props, propName) =>
(typeof props[propName] != 'string') ?
new Error("A title must be a string"):
(props[propName].length > 20) ?
new Erroe('title is over 20 characters'):
null

},
getDefaultProps() {
return {
ingredients:[a,b,c,d],
steps: [1,2,3,4],
title: "[recipe]"
}
},
render() {
const { ingredients, steps, title } = this.props
return (
<div className="summary">
<h1>{title}</h1>
<p>
<span>{ingredients.length} Ingredients</span>
<span>{steps.length} Steps</span>
</p>
</div>

)
}
})

ES6 类时,propTypes defaultProps 是在类的实体之外定义的 一旦定义了类 就可以设置对象属性了。

引用ref 这个特性允许react组件能够和子元素交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Component } from 'react'


class AddColorForm extends Component {
constructor(props) {
super(props)
this.submit = this.submit.bind(this)
}
submit(e) {
const { _title, _color } = this.refs
e.preventDefault();
alert("New Color: ${_title.value} ${_color.value}")
_title.value = '';
_color.value = '#000000';
_title.focus();
}
render() {
return (
<form onSubmit={this.submit}>
<input ref="_title"
type="text"
placeholder="color title..." required/>

<input ref="_color"
type="color" required/>

<button>ADD</button>
</form>

)
}
}

一个文本输入框和一个用于选择十六进制颜色值的按钮来渲染html元素