【问题标题】:ContextProvider => Context APi : Children dynamically renderedContextProvider => Context APi : 儿童动态渲染
【发布时间】:2021-11-16 15:26:20
【问题描述】:

我有一个名为:Register 的函数组件。我用MUI (Material UI for ReactJS)

在其中,我调用了 2 个组件:Step1Step2。两者都使用通过表单收集的数据。

为了简化,我没有发布所有代码。

<RegisterContextProvider>
    {activeStep + 1 === 1 && (<Step1 handleNext={handleNext} />)}
    {activeStep + 1 === 2 && (<Step2 handleNext={handleNext} handleBack={handleBack} />)}
</RegisterContextProvider>

当我点击Step1 内的“下一步按钮”时,我进入MUI STEPPER 组件的下一步并渲染:Step2

Step2RegisterContextProvider的children列表中渲染,Step1从列表中消失,然后Step1表单中存储的数据被重新初始化。

有没有办法将组件包装在更高级别,如下所示:

<RegisterContextProvider>
    <Register/>
</RegisterContextProvider>

谢谢你的建议

【问题讨论】:

    标签: reactjs material-ui react-context


    【解决方案1】:

    您可以创建一个Register 组件,该组件将接收一个对象数组,其中包含步骤组件的数据和当前步骤的索引。

    例子:

    import React, {useMemo} from 'react';
    
    const outOfBoundsOfStepsData = {
        Component: () => (<span>Index out of bounds of array</span>),
        props: {}
    };
    
    const Register = ({steps, index}) => {
        const {Component: Step, props} = useMemo(() => steps[index] || outOfBoundsOfStepsData, [steps, index]);
    
        return <Step {...props} />;
    };
    
    const Step1 = () => {
        // TODO
    };
    
    const Step2 = () => {
        // TODO
    };
    
    const App = () => {
        const steps = [
            {
                Component: Step1,
                props: {
                    handleNext: () => console.log('TODO handleNext')
                }
            },
            {
                Component: Step2,
                props: {
                    handleNext: () => console.log('TODO handleNext'),
                    handleBack: () => console.log('TODO handleBack')
                }
            }
        ];
    
        const index = 0; // TODO
    
        return (
            <RegisterContextProvider>
                <Register steps={steps} index={index}/>
            </RegisterContextProvider>
        );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多