问题描述
大家晚上好,我需要一些帮助。 我无法解决警告:
Keyframes.js:20 id为“sc-isejri”的组件styled.p有 是动态创建的。您可能会看到此警告,因为您已经 在另一个组件中称为样式。要解决此问题,只需创建 任何渲染方法和函数之外的新 StyledComponents 组件。
在此链接 ( https://pastebin.com/a0kMztfD ) 中是我如何使用样式组件的示例。 在复选框文件中,我拥有用于样式组件规则的所有函数,然后我在 App.js 文件中调用这些函数将它们分配给一个 const 变量以在 return() 中使用 我怎么能解决这个问题?它不会为我造成任何错误,但当然会产生一千条警告。
在cards.js中:
export function getCard(Card) {
let fillMode = (Card.style === null) ? 'both' : Card.style.fillMode
let duration = (Card.style === null) ? '1s' : Card.style.duration
const tmp = keyframes`
from,to {
width: ${Card.width};
height: ${Card.height};
background-color: ${Card.colorCard};
background: linear-gradient(${Card.colorCard2},${Card.colorCard});
Box-shadow: 0 16px 16px -8px rgba(0,0.4);
border-radius: 6px;
overflow: hidden;
position: relative;
margin: ${Card.marginCard};
}
`;
const CardFinal = styled.div`
animation: ${duration} ${tmp} ${fillMode};
`;
return CardFinal
}
在 App.js 中:
Const CardContainer = getCard(card1)
return (
<CardContainer></CardContainer>
);
解决方法
问题在于您在 styled.div
函数中创建了一个 getCard
。
消除此警告的方法是将 CardFinal
的创建移到 getCard 之外,并使用 getCard
函数返回您想要生成的任何 css 并稍后将它们作为 props 传递。 Here's how you can pass props with styled-components.
这就是你的代码的样子
const CardFinal = styled.div`
${getAnimation}
`;
export function getCardProps(Card) {
const fillMode = Card.style === null ? "both" : Card.style.fillMode;
const duration = Card.style === null ? "1s" : Card.style.duration;
const tmp = keyframes`
from,to {
width: ${Card.width};
height: ${Card.height};
background-color: ${Card.colorCard};
background: linear-gradient(${Card.colorCard2},${Card.colorCard});
box-shadow: 0 16px 16px -8px rgba(0,0.4);
border-radius: 6px;
overflow: hidden;
position: relative;
margin: ${Card.marginCard};
}
`;
return { fillMode,duration,tmp };
}
const getAnimation = ({ duration,tmp,fillMode }) => {
return css`
animation: ${duration} ${tmp} ${fillMode};
`;
};
现在您只需将 getCardProps
函数用于 CardFinal 期望从 getCardProps
获得的道具。
export default function App() {
const cardProps = getCardProps({
style: null,weight: "100px",height: "100px",colorCard: "grey",marginCard: "10px"
});
return (
<CardFinal {...cardProps}>
YO
</CardFinal>
);
}
Here's a codesandbox link of where you can try & play around to see how it works.
您还可以尝试取消注释 // const WarningDiv
,它基本上复制了您遇到的警告,仅使用返回空 styled.div