簡體   English   中英

如何將字符串參數傳遞給已經有參數的嵌套 function?

[英]How to pass string parameter to nested function, which has already parameters?

這就是我的類別反應功能組件的樣子。 為了更容易測試,我將 handleClick 和 react 組件本身分開——但這不應該是這個問題的問題。

如何將組件字符串值從map()傳遞到handleClick() handleClick已經傳遞了一些操作員參數,這讓我在這個簡單的問題上苦苦掙扎......

export const useCategories = () => {
  const handleClick = (operator) => {
    updateCategory({
      variables: {
        id: '123',
        operator,
        category // <-- this value is missing
      }
    })
  }

  return {
    icon: {
      onClick: handleClick('$pull') // <-- Here I add some operator value
    }
  }
}

export const Categories = () => {
  const { icon } = useCategories()

  return (
      <div>
        {categories.map((category) => <Icon onClick={icon.onClick} />)} {/* <-- how to pass category value to handleClick...? */}
      </div>
  )
}

為了“添加”一個變量,您可以使用currying
因此,返回一個接收新參數並在內部使用它的 function:

export const useCategories = () => {
  return (category) => {
    const handleClick = (operator) => {
      updateCategory({
        variables: {
          id: '123',
          operator,
          category // now this is the argument of the wrapper function
        }
      })
    };

    return () => handleClick('$pull');
  };
}

你可以像這樣使用它:

export const Categories = () => {
  const getOnClick = useCategories();

  return (
      <div>
        {categories.map((category) => {
          const onClick = getOnClick(category);
          return <Icon onClick={onClick} />;
        })}
      </div>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM