React-Native-ListView、ListViewItem(子、父组件互相传值)

首先记录下实现ListView的过程吧http://www.jianshu.com/p/031df20b0e78

 constructor(props) {
        super(props);
        //其中提供给数据源的rowHasChanged函数可以告诉ListView它是否需要重绘一行数据
        // 即数据是否发生了改变,即在需要重绘界面的时候会进行判断
        // 如果之前页面中的改行数据没有发生变化,则不再进行重绘,否则进行重绘
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            //然后通过cloneWithRows方法为其传递一个数组
            dataSource: ds.cloneWithRows(this.getDataArray()),
        };
    }

    //初始化数组数据
    getDataArray () {
        var dataArray = [];

        for (let i = 0 ; i<10 ; i ++) {
            dataArray.push('row' + i);
        }

        return dataArray;
    }


    //子组件向父组件传值需要调用的方法
    onChildChanged (newState) {
    alert(newState);
    }

    //相当于iOS中的cell,返回一个视图布局
    _renderRow (rowData, sectionID,rowID){
        return (

//相当于单独的cell
//rowData、sectionID、rowID是给ListViewItem传的值(父组件向子组件传值)
//callbackParent,是一个方法,用于接收子组件向父组件传的消息
//子组件向父组件回传时,会调用this.onChildChanged这个方法
        <ListViewItem rowData={rowData}
                      sectionID={sectionID}
                      rowID={rowID}
                      callbackParent={this.onChildChanged}/>
        );

    }


//分割线
    _renderSeparator(rowData, sectionID, rowID, highlightRow) {

        return(

            <View style={{backgroundColor:'red',height:1}}></View>

        )
    }

    render() {
        return (

            <ListView style={{flex:1}}
                dataSource={this.state.dataSource}
                renderRow={this._renderRow.bind(this)}
                      renderSeparator={this._renderSeparator.bind(this)}
            />


        );
    }

ListViewItem

//此方法解决 Touchable child must either be native or forward setNativeProps to a native component. 
//参考:http://reactnative.cn/docs/0.20/direct-manipulation.html

    setNativeProps(nativeProps) {
        this.refs._root.setNativeProps(nativeProps);
    }



    render() {

//接收父组件向子组件传的值
        const {rowData,sectionID,rowID} = this.props;

        return (
            <TouchableOpacity ref="_root"
                  style={ListViewItem_TestStyle.itemStyle}
                  onPress={() => {
//在子组件中点击按钮,这里将事件传递给父组件,
                              this.props.callbackParent('你好啊');

                  }}>
//使用传过来的值
                <Text>{'rowdata:'+this.props.rowData}</Text>
                <Text>{'sectionID:'+this.props.sectionID}</Text>
                <Text>{'rowID:'+this.props.rowID}</Text>

            </TouchableOpacity>
        );
    }
}

let ListViewItem_TestStyle =StyleSheet.create({

    itemStyle:{
        height:60,

    }
})

代码地址:https://github.com/chjwrr/React-Native-UI-Test

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值