我创建了一个JS函数,该函数返回带有某些子组件的视图,并且我正在重用代码。我想知道如何将函数传递给由函数创建的组件
const MenuItem = ({title,indicatorColor,index,onPressItem}) => (
<TouchableOpacity onPress={()=>onPressItem(index)} >
<View
style={{
paddingLeft: 20,
paddingBottom: 15,
paddingTop: 15,
flexDirection: 'row',
width: 150,
borderRightWidth: 2,
borderRightColor: 'Colors.GREY_TWO',
backgroundColor: indicatorColor,
alignItems: 'center',
}}>
<View
style={{
backgroundColor: 'black',
height: 5,
width: 5,
borderRadius: 3,
alignSelf: 'center',
}}
/>
<Text style={{fontSize: 15, left: 5,alignItems: 'center',}}>{title}</Text>
</View>
</TouchableOpacity>
);
const onMenuItemPress = (index) => {
console.log('menu selected:'.index);
}
<MenuItem title='Sort' indicatorColor='red' index='0' onPress={onMenuItemPress} />
上面的代码抛出错误,提示onMenuPress不是函数,请提出建议。
Component
中:const MenuItem = ({title,indicatorColor,index,onPressItem}) => {
const onMenuItemPress = (index) => {
console.log('menu selected:'.index);
}
return (
<TouchableOpacity onPress={()=>onPressItem(index)} >
<View
style={{
paddingLeft: 20,
paddingBottom: 15,
paddingTop: 15,
flexDirection: 'row',
width: 150,
borderRightWidth: 2,
borderRightColor: 'Colors.GREY_TWO',
backgroundColor: indicatorColor,
alignItems: 'center',
}}>
<View
style={{
backgroundColor: 'black',
height: 5,
width: 5,
borderRadius: 3,
alignSelf: 'center',
}}
/>
<Text style={{fontSize: 15, left: 5,alignItems: 'center',}}>{title}
</Text>
</View>
</TouchableOpacity>
)
};
<MenuItem title='Sort' indicatorColor='red' index='0' onPress={onMenuItemPress} />