reactjs - 渲染前访问子道具
问题描述
我正在构建一个向导/步骤组件,其中每个子组件都是一个步骤,步骤组件找到应该显示的当前步骤并将其呈现在提供程序中。
我想要实现的下一步是在所有步骤中呈现的组件。我在渲染之前通过子组件道具实现,这样我就可以像这样使用组件:
<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
.
解决方案
推荐阅读
- node.js - AWS 用户数据无法在 Windows Server 2019 上运行
- stata - 如何在 Stata 中为 X 轴创建一个时间变量,以 1920 为年(0)?
- javascript - 如何从其他数组的数字位置获取数组?
- c# - 剪贴板:复制和接收数组
- node.js - Discord Music Bot没有播放问题
- c# - 在 ASP.NET Core 中扩展 IIdentity 接口
- node.js - 在聊天应用程序中,当我们共享链接时,如何加载 url 的信息
- nvidia-jetson - tensorRT YoloV3 Jetson Nano 上的低 FPS
- reactjs - TypeError:urls.map 不是 React 中的函数
- c# - Xamarin 表单可绑定属性条目不起作用