![](/img/trans.png)
[英]How to detect `onClickOutside` and `onEscapeKeyPress` in custom React modal created as a styled component
[英]React styled component specificity issue for modal calling custom styled modal
我正在使用 React 中的樣式化組件。 我想在我的組件中使用以下樣式設置模式樣式,
const StyledModal = styled(Modal)`
.modal-container-header {
display: none;
}
.modal-container-footer {
display: none ;
}
.modal-container-close {
display: none;
}
`;
也就是說,我想為我的自定義模式省略全局頁腳 header。 它適用於一種情況,但不適用於另一種情況。
這是整個組件,
interface LoaderInterface {
loading: boolean;
loadingText?: string;
}
const StyledModal = styled(Modal)`
.modal-container-header {
display: none;
}
.modal-container-footer {
display: none ;
}
.modal-container-close {
display: none;
}
`;
const Loader: FC<LoaderInterface> = ({ loading, loadingText }) => {
console.log("this modal is working");
return (
<StyledModal onClose={() => loading === false} open={loading}>
<div>
<Loading size="large" />
<Heading type="h4">{loadingText}</Heading>
</div>
</StyledModal>
);
};
export default Loader;
在 DEV 工具中,我總是看到,例如,對於頁腳,
.hPyTDi modal-container-footer {
border-top: 1px solid rgba(0,0,0,0.06);
padding: 16px 24px;
text-align: right;
}
這就是全局樣式。 不是我的自定義樣式。 當我在開發工具的上述代碼中應用display: none
時,顯然它正在工作。
但是當 React 功能組件調用我的自定義模式時,這個問題不會持續存在。 僅當模態(也是 React 組件)調用此自定義模態時才會出現此問題。
我也試過 '&' 來增加特異性,但它不起作用。
我做到了
&.modal-container-footer {
display: none;
}
它不起作用。 如果我在全球范圍內移動自定義模態樣式,它就可以工作。 但我不希望這樣,因為這適用於我希望頁眉/頁腳可見的所有模態。
真的很掙扎。 任何幫助深表感謝。
我在 Styled Components 選擇器的方式上遇到了很多問題,並且開始意識到將 props 傳遞給它們總是“更安全”。 這是因為 SC 動態分配 class 名稱的方式。 這可能有幫助嗎?
const StyledModal = styled(Modal)`
${ ({ hidden }) => hidden && `
.modal-container-header, .modal-container-footer, .modal-container-close {
display: none;
}
`}
`;
const Example = () => (
<StyledModal hidden={()=>someFunction} />
)
對於 TypeScript,語法類似:
const StyledModal = styled.div<{hidden: boolean}>(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.