Javascript 停止将道具传递给具有样式化组件的子级
我第一次玩Javascript 停止将道具传递给具有样式化组件的子级,javascript,css,reactjs,styled-components,Javascript,Css,Reactjs,Styled Components,我第一次玩样式化组件,我遇到了“react”传递仅由样式化组件本身使用的道具的问题 以下是我的组件: import { Link } from 'react-router-dom'; const CtaButton = styled(Link)` background: ${props => props.primary ? 'red' : 'yellow'} color: white; display: inline-block; padding: 0.5em 1em;
样式化组件
,我遇到了“react”传递仅由样式化组件本身使用的道具的问题
以下是我的组件:
import { Link } from 'react-router-dom';
const CtaButton = styled(Link)`
background: ${props => props.primary ? 'red' : 'yellow'}
color: white;
display: inline-block;
padding: 0.5em 1em;
`;
当我用primary
属性调用它时,我从react
得到一个警告,我正在将primary
属性应用于
元素。我理解为什么会发生这种情况,但我如何才能阻止它
当然,我可以在剥离该道具的react路由器
链接组件周围创建一个包装器,但这有点笨拙。我确信这只是因为我在这个库的API中还不是一个专业人士,所以有人能给我指出正确的方向吗
由于某些原因,当我直接创建DOM组件时(例如样式化.a
),我没有这个问题。看起来像样式化组件的样式化组件。这不起作用的原因是库在应用于DOM元素时会剥离道具(基于白名单)。对于组件来说,这实际上不可能以同样的方式完成,因为随机组件实际上没有可预测的API
虽然作者和贡献者正在解决这个问题,但这是我提出的解决方案:
import React from 'react';
import { Link } from 'react-router-dom';
const StyledLink = ({ primary, ...rest }) => <Link {...rest} />;
export const CtaButton = styled(StyledLink)`
background: ${props => props.primary ? 'red' : 'yellow'}
color: white;
display: inline-block;
padding: 0.5em 1em;
`;
从“React”导入React;
从'react router dom'导入{Link};
常量StyledLink=({primary,…rest})=>;
export const CtaButton=styled(StyledLink)`
背景:${props=>props.primary?'red':'yellow'}
颜色:白色;
显示:内联块;
填充物:0.5em 1em;
`;
换言之,使用另一个组件包装组件,该组件剥离任何特定于组件的样式道具,然后重新应用其余道具。这并不漂亮,但据我所知,这是最简单的解决方案
您还可以创建一个HOC来为您执行此操作:
const withStrippedProps = propsToRemove => TargetComponent => (props) => {
const strippedProps = Object.entries(props)
.filter(([key]) => !propsToRemove.includes(key))
.reduce((stripped, [key, value]) => ({ ...stripped, [key]: value }), {});
return <TargetComponent {...strippedProps} />
};
const StyledLink = withoutProps(['primary'])(Link);
const CtaButton = styled(StyledLink)`
// css goes here
`;
const withStrippedProps=propsToRemove=>TargetComponent=>(props)=>{
const strippedProps=Object.entries(props)
.filter(([key])=>!propsToRemove.includes(key))
.reduce((剥离,[key,value])=>({…剥离,[key]:value}),{});
返回
};
const StyledLink=withoutProps(['primary'])(链接);
const ctabuton=styled(StyledLink)`
//css在这里
`;
我现在接受这个答案,但如果有任何其他方法不创建这样的包装器组件/函数,我会接受另一个答案