React Native
React Native 看起来很像 React,只不过其基础组件是原生组件而非 web 组件。要理解 React Native 应用的基本结构,首先需要了解一些基本的 React 的概念,比如 JSX 语法、组件、state状态以及props属性。如果你已经了解了 React,那么还需要掌握一些 React Native 特有的知识,比如原生组件的使用。这篇教程可以供任何基础的读者学习,不管你是否有 React 方面的经验。
TextInput
通过 value 属性指定文本内容, 通过 onChangeText 属性监听文本的变化事件
从TextInput谈绑定this传参数
我们在使用TextInput发现每次输入完后;输入的都无效;这是因为要改变没有更改数据源
- 使用箭头函数实现;这样不会改变this的指向
import React from 'react';
import {
View, TextInput, StyleSheet } from 'react-native';
export default class ElseStudy extends React.Component{
constructor(props){
super(props)
this.state = {
myText:'Useless Placeholder'}
}
render(){
return (
<View>
<TextInput
value={
this.state.myText}
onChangeText={
(text)=>this.changeTextHandle(text)}
></TextInput>
</View>
)
}
changeTextHandle(newText){
this.setState({
myText:newText
})
}
}
- 当然代码少,我们可以不用声明一个函数,直接写在
{}
return (
<View>
<TextInput
value={
this.state.myText}
onChangeText={
(myText)=>this.setState({
myText})}
></TextInput>
</View>
)
- 使用bind改变this的指向
render(){
return (
<View>
<TextInput
value={
this.state.myText}
onChangeText={
this.changeTextHandle.bind(this)}
></TextInput>
</View>
)
}
changeTextHandle(newText){
this.setState({
myText:newText
})
}
ScrollView
- 默认情况下, 超出屏幕的内容是看不到的, 不像浏览器环境下会自动添加滚动条
- 如果需要滚动, 可以使用这个组件把要相应的内容包裹起来, 被包裹的内容就会处于滚动条中
- 滚动的过程中,可以通过onScroll绑定回调,每帧最多调用一次回调
import React from 'react';
import {
StyleSheet, Text, View,ScrollView } from 'react-native';
export default class ScrollViewStudy extends React.Component{
constructor(props) {
super(props);
this.state = {
list: ["red", "yellow", "pink", "orange", "blue", "skyblue"]
}
}
render(){
return (
<View>
{
this.state.list.map(color => (
<View
key={
color}
style={
{
backgroundColor: color, width: 300, height: 180}}>
<Text>{
color}</Text>
</View>
))
}
</View>
)
}
}
我们使用View包裹着每个View组件;发现手机只显示中间部分的组件;并不能滚动;我们可以使用scrollView进行包裹
<ScrollView>
{
this.state.list.map(color => (
<View
key={
color}
style={
{
backgroundColor: color, width: '100%', height: 180}}>
<Text>{
color}</Text>
</View>
))
}
</ScrollView>
ScrollView实现轮播
import React from 'react'
import {
StyleSheet, View,ScrollView,Text } from 'react-native';
const Dimensions = require('Dimensions');
const screenSize = Dimensions.get("window");
export default class Lunbotu extends React.Component{
construct