[英]How can I set 2 values for one variable, and the component will render with one value, depending of some prop input
我是新來的,所以如果我的問題不好,請告訴我,以便我進行編輯。
我正在使用 ReactJS + Material UI。 我有一個組件,但我希望根據道具使用不同的屬性渲染該組件,如下所示:
在我要渲染組件的頁面中:
<AdBanner vertical={true} />
在我的 AdBanner 組件中,我有:
export default function AdBanner(props) {
const [adWidth, setAdWidth] = useState("100%");
const [adHeight, setAdHeight] = useState("90px");
const [adSpacing, setAdSpacing] = useState(2);
const [adDirection, setAdDirection] = useState("row");
useEffect(() => {
if (props.vertical) {
console.log("ola");
setAdWidth("320px");
setAdHeight("480px");
setAdSpacing(5);
setAdDirection("column");
}
}, [props.vertical]);
return (
<>
<Paper
variant="outlined"
sx={{ width: { xs: "100%", md: adWidth }, overflow: "hidden" }}
>
...
我的目標是,當我沒有為“垂直”屬性指定值時,我的組件具有某些特征(如高度、寬度……)。 但是在我的應用程序的某些部分,我想要一組其他值用於相同的屬性。
我遇到了一些錯誤,在#guilfer 的幫助下,我能夠消除這些錯誤。
誰能告訴我我所做的是否正確? 謝謝。
這里是完整的代碼: https ://github.com/brunovjk/saude-vapor
謝謝你。
您的代碼中有一些您實際上無法在 javascript 中執行的操作。 當使用“var”定義變量時,它具有全局范圍。 以下是關於差異的解釋: https ://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
在那之后,還有一些我們在 React 中實際上並沒有做的事情,通常在你的情況下,會有兩個不同的類具有你想要的樣式,然后,為了應用樣式,你可以做類似的事情:
import style from "style.module.css" export default function AdBanner(props) { return <div className={props.vertical? style.firstClass : style.secondClass}>banner content<div> }
.firstClass { ...one css styles } .secondClass { ...another css style }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.