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

标签 javascript react-native react-native-ios

我创建了一个 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/

相关文章:

javascript - 如何使用javascript解析字符串并将其按特殊字符分成两部分?

ios - 在 UITableViewCell 中加载 React Native View (RCTRootView)

reactjs - 将参数传递给 `connect()` 中的 mapStateToProps

javascript - Wix react-native-navigation 改变Tab和推屏

facebook - React-native FacebookSDK 显示为带有红色边框的空框

javascript - 如何让页脚固定在底部?

javascript - 在 codeigniter 中有条件地设置 session 数据

javascript - 如何防止我的产品列表在父组件更新时重新呈现?

react-native - React Native 在应用程序最小化但仍处于事件状态之前收到通知

react-native - 如何在 React Native 中以编程方式关闭 ActionSheetIOS?