【问题标题】:how to get style info from parent element? reactjs css如何从父元素获取样式信息?反应js css
【发布时间】:2022-09-22 20:57:33
【问题描述】:

我在按钮组件中有一个文本组件。我想根据按钮的颜色(文本的父级)自动更改文本的颜色如何获取父元素的颜色?在我的文字中我有

const MyText = (props) => {
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const styles = window.getComputedStyle(ref.current).getPropertyValue(\'color\');  //test
  }, [ref]);

  return <MyTextStyled ref={ref} {...props} />;   // styled components 
};

const MyPage = () => {
  return (
   <Button> // my button styled components
     <MyText>Button 1</MyText>
   </Button>
  );
};

如何获取按钮背景颜色以更改文本颜色?以目前的方式,我无法访问父母的样式,我只有我的文字

    标签: javascript css reactjs typescript next.js


    【解决方案1】:

    您可以将 css 样式添加到 Mytext :color: 'inherit'

    【讨论】:

      【解决方案2】:

      在两个组件的父级中设置颜色的状态,然后将状态向下钻取到两个组件,还将 setColor 向下钻取到会更改颜色的组件。这将解决您的问题!

      请参见下面的示例:

      const MyText = (props) => {
        const ref = useRef<HTMLElement | null>(null);
      
        useEffect(() => {
          const styles = props.color;  //test
        }, [props.color]);
      
        return <MyTextStyled ref={ref} {...props} />;   // styled components 
      };
      
      const MyPage = () => {
        const [color, setColor] = useState('blue')
        return (
         <Button color={color} setColor={setColor}> // my button styled components
           <MyText color={color}>Button 1</MyText>
         </Button>
        );
      };

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-15
        • 2011-07-14
        • 2021-12-07
        • 2013-10-14
        • 1970-01-01
        • 2016-10-05
        • 1970-01-01
        相关资源
        最近更新 更多