简体   繁体   中英

Sending prop and then using it as a function in React?

I am trying to send a RouteKey prop and then trying to use the prop inside a chained function.

Here is my Component:

<MenuItem RouterKey={'assetsList'} />

And inside the component definition, I am trying to use it inside the actions function like so :

    import { Actions } from 'react-native-router-flux';
    const MenuItem = (props) => {
  return (
      <TouchableWithoutFeedback onPress={() => { return `${Actions}.${props.RouterKey}()`; }}>
        <View>
         //somethings here...
        </View>
      </TouchableWithoutFeedback>
  );
};

Basically what I want to do is:

<TouchableWithoutFeedback onPress={() => { Actions.whateverWasPassed(); }}>

However, I am not able to do this. What am I missing here? I know the way I am doing it is wrong. What is the correct way to do this?

You can dynamically call any static method by ClassName[methodName]() . It is particularly useful when you have method name as a string. (Just like your case).

So in your case, it will be

<TouchableWithoutFeedback onPress={() => { return Actions[props.RouterKey]();}}>

Another approach that you can follow is, you can directly pass Actions.assetsList method as a prop and invoke it in your MenuItem component.

<MenuItem scene={Actions.assetsList} />

Now, In your MenuItem component, you can invoke this method as props.scene() . Both the approach will work fine.

Here is the link to my answer on a similar question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM