我映射了資料庫中定義的一組顏色。我想將這些顏色作為創建的 div 的背景傳遞。就像我習慣的那樣,控制臺向我展示了陣列中的顏色作為道具傳入。但是在樣式組件中使用道具在打字稿中不起作用。我嘗試了以下,我在網上找到的:
從'styled-components/cssprop'匯入*作為型別
從'styled-components/cssprop'匯入型別{};
/// <reference types="styled-components/cssprop" />
我只將這些變體傳遞到我的檔案中。兩個片段:
<ColorHolder>
{item.colors.map((color)=>(
<div color={color}></div>
))}
</ColorHolder>
CSS:
& div{
width:20px;
height:20px;
border-radius:50%;
background:${props=>props.color};
}
uj5u.com熱心網友回復:
據我了解您的代碼,您不需要使用任何庫。這是作業示例,在colors您從后端獲取的陣列中
<div>
{
colors.map(color=>(
<div style={{backgroundColor: color, height: "50px",width: "50px"}}>
.
</div>))
}
</div>
這是完整的示例-codesandbox.io
uj5u.com熱心網友回復:
只有樣式化的組件才能接收這種樣式適應技術的道具。
因此,在您的情況下,只需創建一個快速樣式div:
const StyledDiv = styled.div<{ color: string }>`
background: ${props => props.color};
`;
<ColorHolder>
{item.colors.map((color) => (
<StyledDiv color={color}></StyledDiv>
))}
</ColorHolder>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510423.html
標籤:反应打字稿样式化组件
