如何通过一种onClick / onPress方法传递2个道具?

时间:2019-03-01 17:59:50

标签: javascript reactjs react-native ecmascript-6 redux

我正在使用React应用,我需要将id传递给在onClick / onPress方法上打开的模式。

下面的组件是我将用来渲染来自数组的某些数据的组件,它是调用模态的组件:

// imports ...

import {
  passengerCardIdAction,
  pickupPassengerCardIdAction,,
} from '../../screens/HomeScreen/actions/homeScreen';

const PassengersInfo = ({
  id, // THIS IS THE ID I NEED
  name,
  address,
  datetime,
  callModal,
  cardinalpoint,
  navigationStore,
}) => {

  return (
    <View>
      <View>
        <View>
         // MAYBE I CAN SET SOMETHING HERE WHERE I GRAB THE ID 
         // ON THE onPress METHOD ALONG WITH THE CALL MODAL FUNCTION
         <TouchableOpacity onPress={callModal}>         
           CALL MODAL
         </TouchableOpacity>
        </View>    
      </View>
    </View>
  );
};

export default compose(
  connect(
    store => ({
      passengerCardId: store.homeScreen.passengerCardId,
      pickupPassengerCardId: store.homeScreen.pickupPassengerCardId,
    }),
    dispatch => ({
      passengerCardIdActionHandler: id => {
        dispatch(passengerCardIdAction(id));
      },
      pickupPassengerCardIdActionHandler: id => {
        dispatch(pickupPassengerCardIdAction(id));
      },       
    }),
  ),
)(PassengersInfo);

然后,在此处调用该组件:

class PassengerCardBasedOnRoute extends Component {

  const { popupsModalsActionHandler, searchParam } = this.props;
  render() {
    return (
     {passengerInfo.map(info => (
      <View key={info.id}>
        <PassengersInfo
          id={info.id}
          name={info.name}
          address={info.address}
          datetime={info.timestamp}
          searchParam={searchParam}
          cardinalpoint={info.cardinalpoint}
          callModal={popupsModalsActionHandler}
        />
      </View>
     )}
    );
  }
};

export default compose(
  connect(
    store => ({
      searchParam: store.homeScreen.searchParam,
      navigationStore: store.homeScreen.navigation,
      passengerCardId: store.homeScreen.passengerCardId,
      allPassengersDropOffOptionsPopup:
        store.popupsModals.allPassengersDropOffOptionsPopup,
      pickupPassengerCardId: store.homeScreen.pickupPassengerCardId,
    }),
    dispatch => ({
      popupsModalsActionHandler: data => {
        dispatch(popupsModalsAction(data));
      },
      passengerCardIdActionHandler: id => {
        dispatch(passengerCardIdAction(id));
      },
      pickupPassengerCardIdActionHandler: id => {
        dispatch(pickupPassengerCardIdAction(id));
      },
    }),
  ),
)(PassengerCardBasedOnRoute);

如果可以的话,我可以获取ID并使用Redux进行设置。 之前,我在PassengersInfo组件中设置了模态信息,但是由于它是一个数组,因此模态被调用了约40次,因为渲染父组件的次数就达到了。

这是我之前所做的:

    return (
     {passengerInfo.map(info => (
      <View key={info.id}>
        <OptionsModal>
          {
            <AllPassengersOptionsModal
              id={info.id}
              handleDeleteOptionsModal={() =>
                this.handleDeletePassenger(info.id)
              }
              handleCallOptionsModal={() =>
                Linking.openURL(`tel:${info.phone}`)
              }
            />
          }
        </OptionsModal>
        <PassengersInfo
          id={info.id}
          name={info.name}
          address={info.address}
          datetime={info.timestamp}
          searchParam={searchParam}
          cardinalpoint={info.cardinalpoint}
          callModal={popupsModalsActionHandler}
        />
      </View>
     )}
    );

因此,以上述方式,我完全按照需要获取数据。那么,如何实现一些东西来获取所需的ID?我需要分别提供每张卡上的信息,因为该模式专门包含诸如deletecall之类的动作。

请参阅我的代码中的注释。

编辑以显示减少器和动作

动作

export const popupsModalsAction = () => ({
  type: ActionTypes.TOGGLE_ALL_PASSENGERS_MODAL,
});

减速器

const initialState = {
  allPassengersDropOffOptionsPopup: false,
};

const handlers = {
  [ActionTypes.TOGGLE_ALL_PASSENGERS_MODAL](state) {
    return {
      ...state,
      allPassengersDropOffOptionsPopup: !state.allPassengersDropOffOptionsPopup,
    };
  },
};

4 个答案:

答案 0 :(得分:1)

只需将箭头函数传递给onPress,就像这样:onPress={() => callModal(this.props.id)}

这是我在一个辅助项目中使用的示例函数:

static propTypes = {
        id: PropTypes.number.isRequired,
        callbackReroll: PropTypes.func.isRequired,
}

rerollButtonPress = () => {
        this.props.callbackReroll(this.props.id);
        this.swipeRowRef.closeRow();
}

render() {
  return(
    <TouchableRipple
    onPress={this.rerollButtonPress}>
       ...
    </TouchableRipple>
  );
}

这样,您可以将prop作为参数传递。

编辑:由于您要使用Redux来控制模式打开和关闭的时间以及显示的数据,因此这是您可以执行的一般示例:

  • 创建一个减速器来处理您的模态
const initialState = {
  shouldModalOpen: false,
  modalData: {},
};

const handlers = {
  [ActionTypes.TOGGLE_MODAL](state, { data }) {
    return {
      ...state,
      shouldModalOpen: !state.shouldModalOpen
      modalData: data,
    };
  },
};
  • 将调用您的模态的组件连接到Redux,并检查shouldModalOpen标志:
<View>
    <OptionsModal>
        {
          this.props.shouldModalOpen
            ? <AllPassengersOptionsModal
              data={this.props.modalData} />
            : null;          
        }
    </OptionsModal>
</View>

答案 1 :(得分:1)

由于您的PassengerCardBasedOnRoute的{​​{1}}道具已经有一个名为popupsModalsActionHandler的参数,请使用该参数发送所需的ID:

data

现在修改<PassengersInfo id={info.id} name={info.name} address={info.address} datetime={info.timestamp} searchParam={searchParam} cardinalpoint={info.cardinalpoint} callModal={() => popupsModalsActionHandler(info.id)} // add which id you want to display in modal /> 动作创建者以在您的动作中添加popupsModalsAction ID:

visiblePassengerId

然后修改您的减速器以存储export const popupsModalsAction = (visiblePassengerId) => ({ type: ActionTypes.TOGGLE_ALL_PASSENGERS_MODAL, visiblePassengerId });

action.visiblePassengerId

现在连接您的Container来监听状态变化: (我不知道您如何定义redux状态,请进行必要的调整)

const initialState = {
  allPassengersDropOffOptionsPopup: false,
  visiblePassengerId: null
};


function modalReducer(state = initialState, action) {
  switch (action.type) {
    case ActionTypes.TOGGLE_ALL_PASSENGERS_MODAL:
      return {
        ...state,
        allPassengersDropOffOptionsPopup: !state.allPassengersDropOffOptionsPopup,
        visiblePassengerId: action.visiblePassengerId // your action has a visiblePassengerId payload now, save it too
      };
    default:
      return state
  }
}

希望有帮助。

答案 2 :(得分:0)

您只需将所需的参数作为参数传递给被调用的函数。

尝试使用带有popupsModalsActionHandler预期参数的选项。

 <TouchableOpacity onPress={() => callModal(id)}>         
   CALL MODAL
 </TouchableOpacity>

答案 3 :(得分:0)

您可以使用匿名函数简单地使用id调用具有id的callModal,或者使用bind将具有id作为其参数的函数传递给它。

<TouchableOpacity onPress={()=>{
  callModal(id)
}}>         
  CALL MODAL
</TouchableOpacity>

OR

<TouchableOpacity onPress={callModal.bind(null,id)}>         
  CALL MODAL
</TouchableOpacity>