首页 > 解决方案 > 渲染前访问子道具

问题描述

我正在构建一个向导/步骤组件,其中每个子组件都是一个步骤,步骤组件找到应该显示的当前步骤并将其呈现在提供程序中。

我想要实现的下一步是在所有步骤中呈现的组件。我在渲染之前通过子组件道具实现,这样我就可以像这样使用组件:

    <Steps >
        <Text> Step 1 </Text> 
        <Text> Step 2 </Text>
        <Text stepless > Stepless </Text>
    </Steps>

我通过像这样编写 Steps 组件来实现它。

export const Steps: React.FC<types.Steps> = ({ step = 0, ...properties }) => {

    /**
     * Global state that store the total number of steps and the current step
     */
    const steps = React.Children.count(properties.children)
    const [state, dispatch] = useReducer(reducer, { step, steps })

    /**
     * Function that will let child components to change the current step
     */
    const next = () => dispatch(types.Action.NEXT)
    const previous = () => dispatch(types.Action.PREVIOUS)

    /**
     * Value to provide to the provider
     * next and previous function to change the current step
     * and the current step
     */
    const value = { next, previous, step: state.step }

    /**
     * Filter the child components that should be shown
     */
    const children = React.Children.toArray(properties.children)
        .filter((child, index) =>
            // @ts-ignore
            (index === state.step) || child?.props.stepless
        )

    return (
        <Context.Provider value={value} >
            { children.map((child, index) => <div key={ index } > { child } </div>) }
        </Context.Provider>
    )
}

但是这段代码对我来说很臭,因为child?.props它不是反应类型的一部分,这让我相信它是在内部使用的,我不应该使用它,但我没有找到其他解决方案来过滤应该在所有步骤中显示的组件。

我正在寻找一种不同的方式来实现相同的行为,而不使用//@ts-ignore.

标签: reactjstypescriptchildrenreact-props

解决方案


推荐阅读