React Native 常用控件

1,首先,要显示控件,需要一个视图画板(View)。React Native绘制视图的组件是 Component。那么,我们就要重载Component对象,制定画板视图,并重载 render() 函数,重新绘制页面时就会调用该方法(详情查看React 组件生命周期),并将UI实现代码放到return中


export default class ThirthDayStudy extends Component {
  render() {
    return (
      // 视图的样式放到styles.container中定义,
      <View style={styles.container}> 
        //  将你的控件代码放到这里…
      </View>
    );
  }
}
// 想了解更多关于属性设置的可以到JavaScript,CSS教程中观摩观摩
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center', // flex-start 容器的开头; flex-end容器的结尾; center容器的中心;  space-between;  space-around
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center', // start end center left right
    margin: 10,
  },
});



2,按照常例,我们要在刚生成的视图里显示 Hello World!文本

     <View style={styles.container}>
        // view中的布局,回默认由上到下添加 所以,text就是最上面的组件(View中)详情可了解React 的页面布局
        <Text style={styles.welcome}> //  styles.welcome 如上面的定义
          Hello World!// React 初始化默认显示 Welcome to React Native!
        </Text>
      </View>


3,显示图片的控件  Image

 <View style={styles.container}>
           …
      <Image
        style={styles.icon}
        source={require('./image/banner.png')}  // 本地图片 根目录/image文件夹/图片名称
      />
      <Image
        style={styles.logo}
        source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} // 网络图片  
      />
           …
      </View>


4, button 按钮及事件 。 在RN中使用按钮有3种:TouchableHighlight,TouchableOpacity,TouchableWithoutFeedback。

TouchableHighlight 点击后产生高亮颜色变化状态;  

TouchableOpacity 点击产生透明度变化状态  点击无变化; 

TouchableWithoutFeedback 官方不推荐使用;


<TouchableHighlight
            style={styles.button}
            onPress={this.onSearchPressed.bind(this)} // 响应方法
            underlayColor='#99d9f4'>  // 高亮颜色
            <Text style={styles.buttonText}>Go</Text>  // 可以在按钮区域显示文本和图片
      </TouchableHighlight>

     // 在 ThirthDayStudy 中添加对应函数
  onSearchPressed() {
    var query = urlForQueryAndPage('place_name', this.state.searchString, 1);
    this._executeQuery(query);
  }

var styles = StyleSheet.create({
   …
    button: {
        width: 100,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        backgroundColor:'#ff0000',
        borderRadius:10   //  圆角
    },
   …
}

     // TouchableOpacity 和 TouchableOpacity 一样 只要设置activeOpacity ,值(如 0.2)即可 
      // 触发事件
onPressIn--用户刚点击
onPressOut--用户手指离开按钮
onPress--用户完成一次点击事件
onLongPress--长按事件
一般来说用户完成一次点击:onPressIn->onPressOut->onPress
但是如果用户按下按钮后移动到按钮外:onPressIn->onPressOut


5,文本输入框

<TextInput
             style={styles.searchInput}
             value={this.state.searchString}
             onChange={this.onSearchTextChanged.bind(this)} // 输入框文本变化是 调用的处理函数
             placeholder='Search via name or postcode'  /> 

…
searchInput: {
     height: 36,
     padding: 4,
     marginRight: 5,
     flex: 4,
     fontSize: 18,
     borderWidth: 1,
     borderColor: '#48BBEC',
     borderRadius: 8,
     color: '#48BBEC'
},
…


重要属性

keyboardType 属性  enum('default', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'email-address', 'decimal-pad', 'twitter', 'web-search', "numeric")   决定打开哪种键盘,例如,数字键盘。 


multiline 布尔型

如果值为真,文本输入可以输入多行。默认值为假。


returnKeyType enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call')

决定返回键的样式


clearButtonMode enum('never', 'while-editing', 'unless-editing', 'always')

清除按钮出现在文本视图右侧的时机


6, 列表 ListView (UITableView)

<ListView
showsVerticalScrollIndicator={false}  // 是否显示滚动条
dataSource={this.state.dataSource.cloneWithRows(this.state.data)}  //  指定数据源
renderRow={(rowData,rowId) => <Text>{rowData}</Text>}  // 每一行的显示 (Cell)
/>

//  在构造函数里,初始化数据源
constructor(props) {
      super(props)

     // row更新的策略
      var dataSource = new ListView.DataSource({
            rowHasChanged:(r1,r2) => r1 != r2,
      })
      // row更新的策略
      this.state = {
            dataSource : dataSource ,
            data : ["A" ,"B" ,"C" ,"D" ,"E" ,"F" ,"G" ,"H"]
      }
  }


7, 滚动视图 ScrollView

<ScrollView
        onScroll={() => { console.log('onScroll!'); }}
        scrollEventThrottle={200}
        contentInset={{top: -50}}
        style={styles.scrollView}>
        
      </ScrollView>

…
contentContainer: { 
backgroundColor: '#6A85B1',
height: 300,
scrollView: 20
 },
…



8, Swiper  用第三方控件 react-native-swiper 。下载该文件放到项目的 ‘node_modules’ 文件夹下面

import Swiper from 'react-native-swiper';

<Swiper height={150} showButtons={true} autoplay={true} 
// 滚动指示点
activeDot={<View style={{backgroundColor: 'rgba(255,255,255,0.8)', width: 8, height: 8, borderRadius: 4, margin: 3}} />} > 
                    <Text style={{flex:1 ,height:150}} >Swiper One</Text>
                    <Text style={{flex:1 ,height:150}} >Swiper tow</Text>
                    <Text style={{flex:1 ,height:150}} >Swiper Three</Text>
              </Swiper>


9, 计时器

let intervel = setInterval( // 开始计时器
            ()=> {

                let currentTime =  (new Date()).getTime()
                let count = currentTime - this.state.intialTime
                let second = Math.floor(count/1000)
                
                this.setState({
                    time: (second<10 ? "0"+second : second),
                })

                if (this.state.buttonTitle == 'Start') { // 在外部改变状态,停止计时器
                    clearInterval(intervel) // 结束计时器
                }
        }, 1000) // 计时器间隔 按 毫秒记


10, tabBarIos

import { TabBarIOS}from 'react-native';

constructor(props) {
        super(props)
        this.state = {
            selectIndex: 0,
            barItems: [{
                title: 'home',
                icon: '',
            } ,{
                title: 'msg',
                icon: '',
            } ,{
                title: 'discover',
                icon: '',
            } ,{
                title: 'member',
                icon: '',
            }]
        }
    }

// 生成 BarItem
baritem(index) {
        return (
            <TabBarIOS.Item
                title={this.state.barItems[index].title} // item 标题
                icon={this.state.barItems[index].icon} // item 图片
                selected={this.state.selectIndex == index}  // item 是否被选中
                onPress={ ()=> {      // item 点击事件
                    this.setState({
                        selectIndex: index
                    })
                }} 
            >
// item 对应的Viewcontroller  继承 Component
                <TabBarViewController nviTitle={this.state.barItems[index].title} />
            </TabBarIOS.Item>
        )
    }

render() {
// 根据数组 生成对应的 BarItem
        var onThis = this
        var items = this.state.barItems.map(function(elem ,index) {
            return (
                onThis.baritem(index)
            )
        })

        return (
            <TabBarIOS barTintColor='#fff' tintColor='#1b95e0' style={{backgroundColor:'#ABC'}} >
                {items}
            </TabBarIOS>
        )
    }



11, RefreshControl 刷新

import {RefreshControl}from 'react-native';
<ScrollView
                refreshControl={<RefreshControl 
                    refreshing={this.state.isRefreshing} // 是否在刷新 ,刷新状态
                    onRefresh={()=> this.refreshAction()} // 刷新触发的事件
                    tintColor='#ff0' />}
            >
                <Text>{this.props.nviTitle + this.state.refreshTime}</Text>
     </ScrollView>


12, PanResponder 手势

import {PanResponder}from 'react-native';

export default class extends Component {
    constructor(props) {
        super(props)
        
        this.state = {
            cicleTop: 64,
            cicleLeft: 0,
        }
    }

    lastLocation = {
        x: 0,
        y: 64,
    }

    stopPan(evt ,gestrueState) {
        this.lastLocation.x = this.state.cicleLeft
        this.lastLocation.y  = this.state.cicleTop
    }

    componentWillMount() {
        this._panResponder = PanResponder.create({
            //用户开始触摸屏幕的时候,是否愿意成为响应者;
            onStartShouldSetPanResponder: (evt ,gestrueState) => true,
            onStartShouldSetPanResponderCapture: (evt ,gestrueState) => true,
            //在每一个触摸点开始移动的时候,再询问一次是否响应触摸交互; 
            onMoveShouldSetPanResponder: (evt ,gestrueState) => true,
            // 开始手势操作。给用户一些视觉反馈,让他们知道发生了什么事情! 
            onPanResponderGrant: (evt ,gestrueState) => {

            },
            // 最近一次的移动距离  gestureState.move{X,Y} 
            onPanResponderMove: (evt ,gestrueState) => {
                var left = this.lastLocation.x + gestrueState.dx;
                var top  = this.lastLocation.y + gestrueState.dy;

                if (left < 0) {
                    left = 0
                }
                if (top < 64) {
                    top = 64
                }
                
                this.setState({
                    cicleTop: top,
                    cicleLeft: left
                })
            },
            // 用户放开了所有的触摸点,且此时视图已经成为了响应者。  
            // 一般来说这意味着一个手势操作已经成功完成。  
            onPanResponderEnd: this.stopPan.bind(this),
            // 用户放开了所有的触摸点,且此时视图已经成为了响应者。
            onPanResponderRelease: this.stopPan.bind(this),
            // 另一个组件已经成为了新的响应者,所以当前手势将被取消。
            onPanResponderTerminate: this.stopPan.bind(this),
        })
    }

    render() {
        return (
            <View style={{flex:1}} >
                <View style={{width:100, height:100, marginTop: this.state.cicleTop ,marginLeft: this.state.cicleLeft , backgroundColor:'#feb'}} {...this._panResponder.panHandlers} >
                </View>
            </View>
        )
    }
}


相关资料

1 http://wiki.jikexueyuan.com/project/react-native/text-input.html react native 教程 

2 https://segmentfault.com/a/1190000004031633  样式使用 

3 http://www.jianshu.com/p/1293bb8ac969 React-Native组件用法详解之ListView 

4 http://www.jianshu.com/p/7944648bb16a ReactNative的ScrollView简述 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章