React提示不识别DOM元素的isSelected prop,如何解决?
解决React警告:"React does not recognize the
isSelected prop on a DOM element" 问题原因
你通过styled-components给原生button元素传递了自定义propisSelected来控制样式,但styled-components默认会把所有传入组件的prop透传给底层DOM元素。而isSelected并不是HTML button的合法原生属性,所以React会抛出该警告。警告偶尔出现是因为初始状态下answers[questionNumber]可能未定义,此时isSelected值为undefined,styled-components不会将无效值传递到DOM;当answers加载完成后,isSelected变为布尔值,才会被传递到DOM触发警告。
解决方案(保留条件样式的同时消除警告)
方案1:使用Transient Props(推荐)
styled-components v5.1及以上版本支持临时属性,只需在prop名前添加$前缀,styled-components就会识别这是仅用于样式逻辑的prop,不会透传给底层DOM元素。
修改ReplyBox的样式定义和使用方式:
// 修改样式定义 const ReplyBox = styled.button` // 其他CSS属性 box-shadow: ${(props) => props.$isSelected ? `0px 0px 0px 2px ${colors.primary} inset` : "none"}; &:first-child { margin-right: 15px; } &:last-of-type { margin-left: 15px; } `; // 使用时传递带$前缀的prop <ReplyBox onClick={() => saveReply(true)} $isSelected={answers[questionNumber] === true} > Oui </ReplyBox> <ReplyBox onClick={() => saveReply(false)} $isSelected={answers[questionNumber] === false} > Non </ReplyBox>
方案2:使用shouldForwardProp过滤属性
通过withConfig方法配置shouldForwardProp,明确指定哪些prop不需要透传给底层DOM元素。这种方式适合需要过滤多个自定义prop的场景。
修改ReplyBox的定义:
const ReplyBox = styled.button.withConfig({ // 仅转发非isSelected的prop shouldForwardProp: (prop) => prop !== 'isSelected' })` // 其他CSS属性 box-shadow: ${(props) => props.isSelected ? `0px 0px 0px 2px ${colors.primary} inset` : "none"}; &:first-child { margin-right: 15px; } &:last-of-type { margin-left: 15px; } `;
使用时无需修改prop名,保持原有的isSelected={...}写法即可,styled-components会自动过滤该prop,不会传递给button元素。
两种方案都能保留基于prop的条件样式逻辑,同时彻底消除React的警告。
内容的提问来源于stack exchange,提问作者Guillaume D.
相关产品推荐
相关产品推荐

