Javascript 如何在React Native中将函数作为属性传递给组件
我已经创建了一个JS函数,它返回一个包含一些子组件的视图,我正在重用代码。我想知道如何将函数传递给由函数创建的组件Javascript 如何在React Native中将函数作为属性传递给组件,javascript,react-native,react-native-ios,Javascript,React Native,React Native Ios,我已经创建了一个JS函数,它返回一个包含一些子组件的视图,我正在重用代码。我想知道如何将函数传递给由函数创建的组件 const MenuItem=({title,indicatorColor,index,onPressItem})=>( onPressItem(索引)}> {title} ); const onMenuItemPress=(索引)=>{ console.log('所选菜单:'.index); } 将函数包装在返回的组件中: const MenuItem = ({title,in
const MenuItem=({title,indicatorColor,index,onPressItem})=>(
onPressItem(索引)}>
{title}
);
const onMenuItemPress=(索引)=>{
console.log('所选菜单:'.index);
}
将函数包装在返回的组件中:
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} />
const MenuItem=({title,indicatorColor,index,onPressItem})=>{
const onMenuItemPress=(索引)=>{
console.log('所选菜单:'.index);
}
返回(
onPressItem(索引)}>
{title}
)
};
常量菜单项=({title,indicatorColor,index,onPressItem})=>(
onPressItem(索引)}>
{title}
);
const onMenuItemPress=(索引)=>{
console.log('所选菜单:'.index);
}
您应该使用onPressItem,而不是onPress-in道具
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' onPressItem={onMenuItemPress} />