2017-03-20 32 views
1

我使用風格的組件樣式組件中的父和子元素:風格元件 - 爲什麼道具位置會影響造型?

function StyledDemo({ 
    name, 
    light, 
    ...props 
}) { 
    return (
    <Parent {...props}> 
     <Child>{name}</Child> 
    </Parent> 
); 
} 

我有一個light道具是真/假 - 但我有與造型基礎元素的問題在該屬性的值:

const Parent = styled.div` 
    background-color: #000; 
    width: 100%; 

    ${props => props.light && ` 
    background-color: #ccc; 
    `} 
`; 

的造型似乎只能當我刪除的道具被傳遞到功能單獨工作。

Parent元素使用基於當light支柱值正確造型:

function StyledDemo({ name, ...props }) 

Parent元素不使用基於light道具價值正確的造型時:

function StyledDemo({ name, light, ...props }) 

我可以得到它的所有工作通過設置ParentChild組件上的支柱,但是這似乎並不像它的最好辦法:

return (
    <Parent {...props} light={light}> 
    <Child light={light}>{name}</Child> 
    </Parent> 
); 

這是應用基於道具樣式組件的正確方法,還是有我的方法的問題嗎?

我有一個演示用,如果它有助於修補: https://www.webpackbin.com/bins/-Kfcsujw99cjU7ttqgTz

回答

1

這是不相關的styled-components但其餘的參數。

當您執行其他操作符時,您按名稱「選取」的任何屬性將不包含在...rest變量中。所以,當你做

const Button = ({ light, ...rest }) =>() 

<Button light primary /> 

rest將只包含primary財產,但不light,這就是現在它自己的變量。

如果你沒有

const Button = ({ ...rest }) =>() 

<Button light primary /> 

代替rest也將包含light

在你的榜樣

所以,你從...props挑選出light,所以當你在父傳{...props}它不包含light了,所以styled-components不知道它的存在!您可以使用第一個版本,或者您必須手動將其應用於每個組件。

有關其餘參數的更多信息,請參閱MDN

相關問題