
class / function 都可以是 "积木" (组件)
import React, {Component} from 'react'
import {Text,View} from 'react-native'
// 类
class GoodMorning extends Component {
render() {
return (
<Text>
Good morning
</Text>
);
}
}
// 函数
const GoodEvening = () => {
return (
<Text>
Good evening
</Text>
);
}
class App extends Component {
render() {
return (
<View>
<GoodMorning />
<GoodEvening />
</View>
);
}
}
使用属性props定制"积木"(组件)
// 类
class GoodMorning extends Component {
render() {
return (
<Text>
Good morning {this.props.name}!
</Text>
);
}
}
// 函数
const GoodEvening = (props) => {
return (
<Text>Good evening {props.name}</Text>
);
}
class App extends Component {
render() {
return (
<View style={styles.container}>
<GoodMorning name="Sir"/>
<GoodEvening name="Madam"/>
</View>
)
}
}
defaultProps默认值和propTypes类型约束
class Demo extends Component {
static defaultProps = {
name: 'somebody', // 赋予默认值'somebody'
}
static propTypes = {
name: React.propTypes.string, // 约定需要的类型(为字符串)
}
render() {
...
}
}
-
defaultProps
和propTypes
写法类似(都为静态成员属性),容易混淆- 建议按英文字面意思来记忆,
default
默认值,types
类型(约束)
- 建议按英文字面意思来记忆,
-
propTypes
类型约束只在开发阶段有效,发布时会被自动移除。- 编码习惯,根据需要和爱好自由取舍。
变量作用域
- 函数内的局部变量,只能函数内读写,函数运行完后销毁(闭包除外)
-
class
内的成员变量,在单个class
的实例内读写,实例销毁时一并销毁- 使用时不要忘记
this
- 使用时不要忘记
-
class
内的静态成员变量,在所有的class
的实例内共享,不会自动销毁。- 其他模块可通过此
class
访问(类public)
- 其他模块可通过此
-
class
外的变量,在所有class
的实例内共享(共有),不会自动销毁- 除非明确
export
,否则其他模块不可访问(类private)
- 除非明确
-
global
全局变量,任何地方可读写(类浏览器的window)
,不会自动销毁
class内的成员变量写法
// class类写声明的东西,不能写完整的语句
class Demo extends Component {
xxx = 1; // 注意没有声明符号var或者let
render() {
...
}
}
// 和上面是同样的效果
class Demo extends Component {
constructor(props) {
super(props); // 照抄即可,不可省略
this.xxx = 1;
}
render() {
...
}
}
动态列表与key
- 根据多个数据(数组)动态生成多个组件一般使用map方法
- 注意箭头函数的返回值(有{}则必须写return)
- 循环生成的组件需要有唯一的key值区分(Virtual DOM)
- key属性放在循环的直接容器上
- 优先使用区分度高的属性(id,具体内容等),其次选择数组下标
- 只需在当前循环中唯一不重复
在不添加大括号的时候,箭头函数会默认return语句
网友评论