您的位置:首页 > 其它

Touchable类型的组件的子组件为复合类型时出现的错误解决

2016-08-27 21:05 274 查看

先上代码

//渲染方法
renderRow(rowData,sectionID,rowID,highlightRow) {
return (
<TouchableHighlight
onPress={() => {
this._rowPressed(sectionID, rowID);
}
}
style={{}}
underlayColor='red'>
<IndexListViewItem rowData={rowData} sectionID={sectionID} rowID={rowID}/>
</TouchableHighlight>

);
}

//IndexListViewItem自定义组件
'use strict';

import React, { Component } from 'react';

import {
StyleSheet,
View,
Text,
} from 'react-native';

class IndexListViewItem extends Component {
render() {
return (
<View style={{flexDirection: 'row',justifyContent: 'center',backgroundColor: '#F6F6F6',}}>
<Text  style={{fontSize: 18}}>
{this.props.rowData}
</Text>
</View>
);
}
}

const styles = StyleSheet.create({

});

export default IndexListViewItem;


这里直接运行会报错:touchable child must either be native or forward setnativeprops to a native component。

总结出错的原因是,Touchable类型的组件会自动给子组件传递一些props,但是这些props只支持原生组件,如果是自定义的复合组件就会出问题。就好像你给自定义的复合组件直接设置style,那这个style到底是设置到复合组件的哪个子组件上呢?就会有问题,解决办法就是在自定义的复合组件里使用setNativeProps方法把Touchable设置的props传递给自定义复合组件内部的原生子组件。

1、在子组件内部添加如下代码

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


2、在子组件内部的第一个子原生组件中添加如下属性

ref={component => this._root = component}


3、如果Touchable类型是TouchableOpacity,还需要在子组件内部添加如下代码,用来传递props

{...this.props} //新语法,相当于取出所有的props


PS、为什么要添加第三条还没搞太明白,希望有高手能指教一下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐