【问题标题】:How do I conditionally render the color of my component based on the prop?如何根据 prop 有条件地渲染组件的颜色?
【发布时间】:2022-01-10 03:37:27
【问题描述】:

我的组件的颜色会根据道具“级别”的值而变化。当我尝试使用状态设置背景颜色时,我意识到所有组件都具有相同的颜色,因为状态会随着每条评论的变化而不断变化。我尝试使用引用和状态来解决这个问题,但是我无法解决问题,因为代码似乎工作相同。任何帮助都会很棒,谢谢。

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,
        }

【问题讨论】:

    标签: javascript css reactjs react-native styles


    【解决方案1】:

    我会删除 state、useEffect 和 ref,因为它们使组件过于复杂。

    而是根据 level 的值设置背景颜色。最好的方法与您在 useEffect 中所做的类似,但将其放入常规函数中。

    类似:

    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 = () => StyleSheet.create({
        container:{
            backgroundColor: getBackgroundColor(),
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用useEffect 的第二个参数来告诉它何时运行(by default it runs on each update)。我假设您想根据您的代码将level 作为第二个参数传递,以便useEffect 仅在level 更新时运行。

      useEffect 与第二个 arg 一起使用的格式如下:

               useEffect(() => {
                    console.log(state); 
                    //value of state is used here therefore must be passed as a dependency
               }, [state])
      

      【讨论】:

      • 感谢您的帮助
      猜你喜欢
      • 2017-02-22
      • 2021-10-05
      • 2022-12-13
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多