首页 > 解决方案 > styled-components:如何防止道具被发送到链接组件?

问题描述

我正在使用样式化组件来设置我的链接样式。我有时还需要使用Link来自react-router-dom.

import { Link } from 'react-router-dom';
import { Anchor } from './src';

export const StyledLink = Anchor.withComponent(Link);

但是,上面的代码会在控制台中产生以下警告:

警告:收到true非布尔属性unstyled

如果要将其写入 DOM,请改为传递字符串:unstyled="true" 或 unstyled={value.toString()}。

unstyled是一个被传递给StyledLink这样的道具:

<StyledLink unstyled />

这个警告是由Link组件生成的,是因为unstyledprop 被传递给 DOM 元素Link

所以,问题是,如何防止Link尝试向元素添加道具?

标签: react-router-domstyled-components

解决方案


的目的Styled Component是为具有原始道具的透明组件提供服务(参考:https ://www.styled-components.com/docs/basics#passed-props )。您正在寻找的模式是一个HoC(参考:https ://reactjs.org/docs/higher-order-components.html ),它返回一个样式(或非样式,基于道具)组件。


推荐阅读