我创建了一个 JS 函数,它返回带有一些子组件的 View ,并且我正在重用代码。我想知道如何将函数传递给由函数创建的组件
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 不是函数,请提出建议。
最佳答案
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} />
你应该在 props 中使用 onPressItem 而不是 onPress
关于javascript - 如何在 React Native 中将函数作为属性传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59724067/