![](/img/trans.png)
[英]How do I conditionally render a component in Gatsby based on specific page?
[英]How do I conditionally render the color of my component based on the prop?
我的組件的顏色會根據道具“級別”的值而變化。 當我嘗試使用狀態來設置背景顏色時,我意識到所有組件的顏色都與 state 的顏色相同,因為每條評論都會不斷變化。 我嘗試使用引用和狀態來解決這個問題,但是我無法解決問題,因為代碼似乎工作相同。 任何幫助都會很棒,謝謝。
function CommentMargin({level}) {
const [marginColorState, setMarginColorState] = useState(colors.lightPurple);
const marginColor = useRef(null);
useEffect(() =>
{
switch (level) {
case 1:
setMarginColorState(colors.lightPurple);
marginColor(marginColorState);
case 2:
setMarginColorState(colors.crimson);
marginColor(marginColorState);
case 3:
setMarginColorState(colors.orange);
marginColor(marginColorState);
case 4:
setMarginColorState(colors.yellow);
marginColor(marginColorState);
}
}
)
return (
<View style={styles(marginColor).container}>
</View>
);
}
export default CommentMargin;
const styles = (marginColor) => StyleSheet.create({
container:{
backgroundColor: marginColor.current,
}
您可以使用useEffect
的第二個參數來告訴它何時運行( 默認情況下它在每次更新時運行)。 我假設您想根據您的代碼將level
作為第二個參數傳遞,以便useEffect
僅在level
更新時運行。
將useEffect
與第二個 arg 一起使用的格式如下:
useEffect(() => {
console.log(state);
//value of state is used here therefore must be passed as a dependency
}, [state])
我將刪除 state、useEffect 和 ref,因為它們使組件過於復雜。 而是根據 level 的值設置背景顏色。 最好的方法類似於您在 useEffect 中所做的,但將其放入常規的 function 中。 就像是:
const getBackgroundColor = () =>{ switch (level) { case 1: return colors.lightPurple case 2: return colors.crimson case 3: return colors.orange case 4: return colors.yellow } } const styles = (marginColor) => StyleSheet.create({ container:{ backgroundColor: getBackgroundColor(), }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.