防止在样式组件中将道具从子级传递给父级

Prevent pass props from child to parent in styled components

我在 TypeScript 中使用样式化组件库。我在创建继承自 React 组件 A 的样式化组件 B 时遇到问题。 A 是 node_module(我无法更改 A 的行为)。但是 A 将所有道具传递给 div.

如果 B 有任何 A 没有的属性,控制台会显示警告消息,因为 div 没有属性 isExpanded:

Warning: React does not recognize the isExpanded prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase isexpanded instead. If you accidentally passed it from a parent component, remove it from the DOM element.

interface AProps {

}

interface BProps {
    isExpanded: boolean
}

const A = (props: AProps) => (
    <div {...props} />
) // Component A pass all props to <div>

const B = Styled(A)<BProps>`

` // I need isExpaned prop in component B and I would like to interit from A

有什么方法可以防止 "bubble" 在样式组件中从子级到父级的道具?

在样式组件中没有针对此的内置解决方案,但您可以将其包装到函数组件中并解构不需要的属性。

const B = Styled(({isExpanded, ...props})=><A {...props}/>)<BProps>`

您还可以查看有关此主题的 github-issue:https://github.com/styled-components/styled-components/issues/135