您的位置:首页 > Web前端 > React

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

2017-04-05 22:02 531 查看
首先记录下实现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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: