如何在 React(使用 TypeScript)中创建具有灵活操作的自定义操作栏?
我想创建一个具有灵活动作的自定义动作栏,可以通过道具设置或类似的操作。
这就是我实施它的方式(并且它的工作原理),但是我想知道是否有更好或更清洁的React方法(使用Typescript)。
特别是当动作随着时间而增加时。然后,我将不得不添加更多的布尔人,最终会使事情令人困惑。
type CustomBarProps = {
withButton: boolean,
withCheckbox: boolean,
withRadio: boolean,
}
export const CustomBar = ({
withButton = false,
withCheckbox = false,
withRadio = false,
}: CustomBarProps) => {
const features: JSX.Element[] = [
withButton && <Button />,
withCheckbox && <Checkbox />,
withRadio && <Radio />,
]
return <Bar features={features} />
}
I would like to create a custom action bar with flexible actions that can be set via props or similar.
This is how I implemented it (and it's working like expected), but I'm wondering if there's a better or cleaner way in React (with TypeScript).
Especially when the actions increase over time. Then I would have to add more booleans that would eventually make things confusing.
type CustomBarProps = {
withButton: boolean,
withCheckbox: boolean,
withRadio: boolean,
}
export const CustomBar = ({
withButton = false,
withCheckbox = false,
withRadio = false,
}: CustomBarProps) => {
const features: JSX.Element[] = [
withButton && <Button />,
withCheckbox && <Checkbox />,
withRadio && <Radio />,
]
return <Bar features={features} />
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您不需要明确定义每个道具必须是错误的,您也可以这样做
yeah you don't need to explicitly define each prop has to be false you can also do it like this