[英]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. 我正在尝试发送
RouteKey
道具,然后尝试在链接函数中使用道具。
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]()
. 您可以通过
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. 您可以遵循的另一种方法是,可以直接将
Actions.assetsList
方法作为道具传递,并在MenuItem
组件中调用它。
<MenuItem scene={Actions.assetsList} />
Now, In your MenuItem
component, you can invoke this method as props.scene()
. 现在,在
MenuItem
组件中,您可以将该方法作为props.scene()
调用。 Both the approach will work fine. 两种方法都可以正常工作。
Here is the link to my answer on a similar question. 这是我对类似问题的回答的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.