[英]!important inline styles in react
有沒有一種方法可以使用?重要的覆蓋來添加內聯樣式?
style={
height: 20+'!important'
};
<div style={style}></div>
這不像我希望的那樣有效。
顯然 React 不支持這一點。 但是我在研究時得到了這個黑客
<div ref={(node) => {
if (node) {
node.style.setProperty("float", "right", "important");
}
}}>
</div>
祝你好運:)
20+'!important'
是'20!important'
。
當你只給一個數字時,react 會為你添加“px”; 但是您使用的是字符串,因此您必須指定單位。 此外,我很確定“!important”和它左邊的任何東西之間需要有一個空格。
style={{ height: '20px !important' }};
一個很好的使用技巧,它對其他 CSS 屬性更清晰、更一致:
ref={(el) => el && el.style.setProperty(<property>, <value>, "important")}
希望這可以幫助!
這是我可以讓它與 React 16 一起工作的唯一方法。
const id="unique_id";
<React.Fragment>
<style>
{`
#${id} {
background-color: transparent !important;
}
`}
</style>
<Frame id={id} />
</React.Fragment>
如果您有充分的理由使用!important
,我建議使用樣式組件,因為樣式道具不支持!important
並且將來可能不會支持。
這是一個示例,我們在grid columns
上覆蓋 Semantic-UI 的padding
。 您實際上可以省略!important
,因為“ 提高特異性”就足夠了。
const StyledColumn = styled.div(({size}) => ({className: `${size} wide column`})`
&&&&& {
padding-top: 0.3rem !important;
padding-bottom: 0.3rem !important;
}
`
<StyledColumn size="three"></StyledColumn>
&&&&&& <- 提高特異性。
是的,我發現這樣做的方式是上面已經提到的:
const styles = (theme: any) => ({
panelSize: {
height: 480,
width: 360,
},
progress: {
height: '120px !important',
margin: theme.spacing.unit * 2,
width: '120px !important'
}
});
上面的丹尼爾最初回答了這個問題。 我只是想分享我的答案,因為我重構了他的答案以使用鈎子。
const ref = useRef(null);
<div ref={ref}></div>
ref.current.style.setProperty(<property>, <value>, "important")
請參閱下面的示例代碼
import React, { useRef, useLayoutEffect } from "react";
const SampleComponent = () => {
const ref = useRef(null);
useLayoutEffect(() => {
ref.current.style.setProperty("border-top", "0px", "important");
}, []);
return (
<div ref={ref}>
{/* additional codes here */}
</div>
)
}
筆記:
我嘗試了上述關於寬度的建議,但無法使其正常工作。
這對我有用,我創建了 style.css 文件,並在我的情況下添加了 width: 100% !important 到一個類,然后將該文件導入到我的組件中,然后調用這個類,它就可以工作了。
在材料Ui文檔中提到了另一種更清晰的方法,可以與react一起使用以覆蓋默認行為
1-為樣式聲明一個常量變量
const widthStyle = {
width:10
}
2-將它與JSX一起用於內聯樣式
<div style={widthStyle}></div>
使用現代語法對代碼進行了一些改進,以使代碼更短:
<div ref={(node) =>
node?.style.setProperty("float", "right", "important")
}>
</div>
我通過設置 className 道具解決了它
.height {
height: 20px !important;
}
className={ styles.height }
我能夠通過做這樣的事情來解決它:
style={
height: `20px ${" !important"}`
};
<div style={style}></div>
我必須在“.important”之前添加空格,因為瀏覽器在運行程序時會不斷刪除該空格。
有沒有一種方法可以使用!important覆蓋添加內聯樣式?
style={
height: 20+'!important'
};
<div style={style}></div>
這不是我希望的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.