如何在React Native中将函数作为属性传递给组件

问题描述 投票:0回答:1

我创建了一个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不是函数,请提出建议。

javascript react-native react-native-ios
1个回答
0
投票
将函数包装在返回的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} />

© www.soinside.com 2019 - 2024. All rights reserved.