【问题标题】:Pass props to a component that is returned from a variable将道具传递给从变量返回的组件
【发布时间】:2022-12-22 20:06:21
【问题描述】:

大家好,我一直在使用“WebDev Simplified”中的这个钩子

import { ReactElement, useState } from 'react';

export function useMultistepForm(steps: ReactElement[], initialStep = 0) {
  const [currentStepIndex, setCurrentStepIndex] = useState(initialStep);

  function next() {
    setCurrentStepIndex((i) => {
      if (i >= steps.length - 1) return i;
      return i + 1;
    });
  }

  function back() {
    setCurrentStepIndex((i) => {
      if (i <= 0) return i;
      return i - 1;
    });
  }

  function goTo(index: number) {
    setCurrentStepIndex(index);
  }

  return {
    currentStepIndex,
    step: steps[currentStepIndex],
    steps,
    numberOfSteps: steps.length,
    isFirstStep: currentStepIndex === 0,
    isLastStep: currentStepIndex === steps.length - 1,
    goTo,
    next,
    back,
  };
}

所以我想做的是找出一种方法将 goTo() 函数传递给最后一个元素是 Steps 这就像一个摘要,这样我就可以有一些链接或按钮将用户带到那个特定页面,让他们在那里修改一些东西。

我读过 React.cloneElement 可以使用,但我也在 react 文档中看到“使用 cloneElement 并不常见并且会导致代码脆弱。”所以任何建议都会很好。

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    步骤组件应配置为接受 goTo 或其他道具。

    const StepElm = ({ goTo }) => {
      return <p>Test message</p>;
    };
    

    然后你将把这些元素传递给钩子:-

    const { step } = useMultistepForm([StepElm]);
    

    在 useMultistepForm 钩子中:更改如下。

    const processedSteps = steps.map((step) => step({ goTo }));
    return {
    step: processedSteps[currentStepIndex],
    steps: processedSteps,
    ...
    }
    

    在上次使用中可以使用以下步骤:-

    const { step } = useMultistepForm([StepElm]);
    
    return (
      <div>
        {step}
      </div>
    )
    

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2020-01-08
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2021-11-02
      • 2018-07-07
      相关资源
      最近更新 更多