自定义组件中使用 props, 在 render 函数中引用 this.props 即可
- import React, { Component } from 'react';
- import { Text, View } from 'react-native';
- class Greeting extends Component {
- render() {
- return (
- <View style={{alignItems: 'center', marginTop: 50}}>
- <Text>Hello {this.props.name}!</Text>
- </View>
- );
- }
- }
- export default class LotsOfGreetings extends Component {
- render() {
- return (
- <View style={{alignItems: 'center'}}>
- <Greeting name='Rexxar' />
- <Greeting name='Jaina' />
- <Greeting name='Valeera' />
- </View>
- );
- }
- }
- 2.state
工作原理与 react 一致;
必须使用 setState 改变状态;
setState 是一个 merge 合并操作, 不会影响其他属性;
setState 是一个异步操作, 也就是说修改不会立即生效.
3. 样式
样式名基本遵循了 CSS 的命名规则, 只是要求小驼峰命名;
在 JS 文件中声明一个 styles 对象即可使用
- const styles = StyleSheet.create({
- bigBlue: {
- color: 'blue',
- fontWeight: 'bold',
- fontSize: 30,
- },
- red: {
- color: 'red',
- },
- });
4. 高度和宽度
指定宽高: 无单位, 表示逻辑像素点
弹性 (Flex) 宽高: 要求父组件有设置 width, height 或者 flex, 容器尺寸不能为 0
Flex 布局
flexDirection alignItems justifyContent
与 web 上的 CSS 的差异不大, 差异在于默认值: flexDirection 默认值不再是 row 而是 column, 然后 flex 值只能是数值.
- flex
- will define how your items are going to **"fill"** over the available space along your main axis. Space will be divided according to each element's flex property.
详情点击
文本输入处理
onChangeText: 此属性接受一个函数, 而此函数会在文本变化时被调用;
onSubmitEditing: 在文本被提交后 (用户按下软键盘上的提交键) 调用;
- import React, { Component } from 'react';
- import { Text, TextInput, View } from 'react-native';
- export default class PizzaTranslator extends Component {
- state = {
- text: ''
- }
- render() {
- return (
- <View style={{padding: 10}}>
- <TextInput
- style={{height: 40}}
- placeholder="Type here to translate!"
- onChangeText={(text) => this.setState({text})}
- value={this.state.text}
- />
- <Text style={{padding: 10, fontSize: 42}}>
- {this.state.text.split('').map((Word) => Word &&'').join(',')}
- </Text>
- </View>
- );
- }
- }
触摸事件处理
RN 提供了常见的手势操作, 如滑动, 点击等, 同时也提供了识别更复杂的手势的完整的手势响应系统.
<Button onPress={() => { Toast.show('Clicked')}} title='Click Here' />
8. 滚动视图
ScrollView 适合用来显示数量不多的滚动元素, 放在其中的所有元素都会被渲染, 所以不是很推荐使用, 性能更好的组件可以使用 FlatList
9. 长列表 FlatList 或 SectionList
优势: 相比于 ScrollView 全部元素渲染, FlatList 优先渲染当前屏幕的元素.
FlatList 组件必须的两个属性是 data 和 renderItem.data 是列表的数据源, 而 renderItem 则从数据源中逐个解析数据, 然后返回一个设定好格式的组件来渲染.
- <FlatList
- keyExtractor={ item => item.name }
- data={ items }
- renderItem={ ({ item }) => this.renderItem(item) }
- />
Section: 渲染分组数据可选择
- export default class SectionListBasics extends Component {
- render() {
- return (
- <View style={styles.container}>
- <SectionList
- sections={[
- {title: 'D', data: ['Devin', 'Dan', 'Dominic']},
- {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
- ]}
- renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
- renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
- keyExtractor={(item, index) => index}
- />
- </View>
- );
- }
- }
9. 网络请求
- fetch
- fetch('https://mywebsite.com/endpoint/', {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- firstParam: 'yourValue',
- secondParam: 'yourOtherValue',
- }),
- });
处理响应数据
- function getMoviesFromApiAsync() {
- return fetch('https://facebook.github.io/react-native/movies.json')
- .then((response) => response.JSON())
- .then((responseJson) => {
- return responseJson.movies;
- })
- .catch((error) => {
- console.error(error);
- });
- }
抑或使用 ES7 的 async/await 语法
- // 注意这个方法前面有 async 关键字
- async function getMoviesFromApi() {
- try {
- // 注意这里的 await 语句, 其所在的函数必须有 async 关键字声明
- let response = await fetch(
- 'https://facebook.github.io/react-native/movies.json',
- );
- let responseJson = await response.JSON();
- return responseJson.movies;
- } catch (error) {
- console.error(error);
- }
- }
来源: http://www.jianshu.com/p/3ade22b3dd2f