简体   繁体   English

如何将 function(在数组内)作为 prop 传递给 React 中的子组件

[英]How to pass a function (within an array) as a prop to a sub component in React

Is it possible to do something like this in React?有可能在 React 中做这样的事情吗? (see comments in the code below): (请参阅下面代码中的注释):

/* Within Parent Component */
// `1` is a constant, `(i:any) => i` is a variable from the `for` loop in the child component. These 2 values need to be added
<SubComponent position={[(1 + (i:any) => i, 2]} />

...
/* Sub Component */
export default function SubComponent({ position }: {position: number[]}) {

    const object;
    count = 2;

    for (let i = 0; i < count; i++) {
      // todo I don't think `position[0](i)` is a valid syntax, but I want to pass the value of `i` to the function within the `position` array (and then add the constant `1`).
      object.position.set(position[0](i), position[1]);
      
...

// value of object.position:
1. [1,2]
2. [2,2]

If this doesn't make sense, I will amend the question, but something in the back of my mind is telling me to look into 'currying' as a possible solution, is this the right thing to Google for this scenario?如果这没有意义,我会修改这个问题,但我脑海中的某些东西告诉我要研究“柯里化”作为一种可能的解决方案,对于这种情况,谷歌是正确的选择吗?

Figured it out, will leave it here in case it helps someone else:想通了,将它留在这里以防它帮助别人:

<SubComponent position={[(i:number) => {return 1 + i}, 2]}

...

export default function SubComponent({ position }: {position: number[]}) {

    const object;
    count = 2;

    for (let i = 0; i < count; i++) {
      object.position.set(position[0](i), position[1]);

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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