【问题标题】:TypeScript how to trigger action in a component from the another oneTypeScript 如何从另一个组件触发组件中的操作
【发布时间】:2020-07-22 06:53:26
【问题描述】:

我使用 Ant Design 并通过单击“antd”按钮来触发自定义“antd”步骤组件中的更改步骤。我该怎么做呢?谢谢! (https://ant.design/components/button/) + (https://ant.design/components/steps/)

const StepOne = ({ onClick }: any) => {
              return (
                <div>
                  <Button type='primary' onClick={onClick}>
                    StepOneLogIn
                  </Button>
                  <Button>StepOneRegister</Button>
                </div>
              );
            };
export const Order = () => {
          const [currentStep, setCurrentStep] = useState(0);

          //Final
          return (
            <div>
              <Steps size='small' current={currentStep}>
                <Step title='text' />
                <Step title='text' />
                <Step title='text' />
                <Step title='text' />
              </Steps>

              <Divider />
              <div>
                {currentStep === 0 ? (
                  <StepOne onClick={setCurrentStep(currentStep + 1)} />
                ) : null}
              </div>
              <div>{currentStep === 1 ? <StepTwo /> : null}</div>
              <div>{currentStep === 2 ? <StepThree /> : null}</div>
              <div>{currentStep === 3 ? <StepFour /> : null}</div>
            </div>
          );
        };

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您不小心将setCurrentStep 的返回值而不是函数传递给onClick 处理程序。你应该改变

    &lt;StepOne onClick={setCurrentStep(currentStep + 1)} /&gt;

    到这里

    &lt;StepOne onClick={() =&gt; setCurrentStep(currentStep + 1)} /&gt;

    () =&gt; setCurrentStep(currentStep + 1) 创建一个函数,它将调用您的 setCurrentStep 函数,并将该函数传递给 onClick 属性,而您之前的代码直接调用 setCurrentStep 并将其返回值传递给 @ 987654329@ prop,导致按下按钮时没有任何反应。

    除此之外,您的其余代码看起来适合尝试从您的孩子StepOne 组件触发操作

    【讨论】:

    • 知道了!非常感谢,在您的帮助下我解决了这个问题!
    • @NikolaiMelnikov 没问题
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 2017-03-11
    • 2021-01-20
    • 1970-01-01
    • 2021-03-30
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多