簡體   English   中英

在樣式組件 React 中忽略父樣式的 CSS

[英]Ignoring CSS from parent style in styled-component React

我正在使用使用樣式化組件的現有組件庫創建一個 React 組件。 我有時需要覆蓋父庫中的樣式並使用我自己的樣式。 這是庫中具有樣式的 TextInput 組件,

border: 2px solid black;

在使用此組件時,我不想在輸入框周圍設置邊框。 相反,我只想要一個下划線。

我用兩種方式做到了,使用風格道具

<TextInput
name="test-input"
value={testInput}
onChange={onInputChange}
style={{borderTop: 'none',borderRight: 'none',
borderLeft:'none', borderBottom: '2px solid black'}}
/>

這樣我得到了一個黑色的底部邊框,但它需要我對所有其他三個重復。 有沒有更好的方法讓我可以寫一行來解決我的問題?

我基於現有組件創建了一個樣式化組件,

const TextInputStyled = styled(TextInput)`
border-top: none;
border-right: none;
border-left: none;
border-bottom: 1px solid black`;

在這里,我的組件具有上述樣式。

<TextInputStyled
                name="test-input"
                value={testInput}
                onChange={onInputChange}
            />

在這種情況下,我得到了 2px 黑色的 border-bottom,但另一個 border 也存在,這也是一個重復。

有更好的方法嗎? 我經常需要抽動父組件的樣式。

很感謝任何形式的幫助。

你為什么不試試這個代碼:

<TextInput
name="test-input"
value={testInput}
onChange={onInputChange}
style={{border:'unset', borderBottom: '2px solid black'}}
/>

更新:

如果你堅持使用樣式組件,ThemeProvider 是解決方案:


const TextInput=styled.input `
border: 2px solid black;
border-bottom:  ${props => props.theme.borderBottom};
border-top:${props => props.theme.borderTop};
border-left:${props => props.theme.borderLeft};
border-right:${props => props.theme.borderRight};
`;

       \\Define what props.theme will look like
 const theme= {
    borderTop: 'none;',
    borderRight: 'none;',
    borderLeft: 'none;',
    borderBottom: '1px solid black;'
  }
return(<>
  \\normal TextInput with border
 <TextInput
name="test-input"
/>


     \\customized TextInput without border except underline
 <ThemeProvider theme={theme}>
  <TextInput
name="test-input"



/>
</ThemeProvider>
</>
)


如果您不了解 ThemeProvider,請閱讀這篇文章:

https://styled-components.com/docs/advanced

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM