reactNative基础3

元素对其方式

元素对其方式就是元素相对于父元素的位置,默认情况下元素在纵轴的最上边,横轴的最左边,不过通过样式可以改变元素在父容器的位置。

1
2
3
4
5
// 主轴对其方式
justifyContent: flex-start flex-end center space-between space-around

// 交叉轴对其方式
alignItems: flex-start flex-end center stretch
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
34
35
export default class FlexAlignTest extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.one}></View>
<View style={styles.two}></View>
<View style={styles.three}></View>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
width: 500,
justifyContent: "center",
alignItems: "center"
},
one: {
height: 100,
width: 100,
backgroundColor: "red"
},
two: {
height: 100,
width: 100,
backgroundColor: "green"
},
three: {
height: 100,
width: 100,
backgroundColor: "blue"
}
});

feach

RN提供了和web标准一致的网络请求API,XMLHttpRequest与Fetch,Fetch用起来将对比较容易,且支持Promise,所以一般会选用Fetch。

1
2
// 豆瓣电影top250: http://api.douban.com/v2/movie/top250
// 豆瓣电影详情: http://api.douban.com/v2/movie/top250/movie/subject/:id

发起一个get请求

1
2
fetch('http://api.douban.com/v2/movie/top250')
.then((response) => console.log(response));

发起一个post请求,并携带参数,需要使用Fetch第二个options参数

1
2
3
4
5
6
7
8
9
fetch('http://api.douban.com/v2/movie/top250', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({a:1, b:2})
})
.then((response) => console.log(response));

fetch返回的Promise对象,添加的成功回调拿到的是response对象,里面的数据默认是文本,一般我们请求回来的数据是json对象,
可以使用response对象提供的json方法转换,该转换方法同样返回一个Promise对象,所以一般我们需要两次then,在第二个then里拿到对象数据。

1
2
3
4
5
6
7
8
fetch('http://api.douban.com/v2/movie/top250')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
分享