React中能否获取元素特定CSS属性值并动态修改样式?
Great question! Let's break this down—what you're trying to do makes total sense, but there's a key detail about how React handles styles and DOM interactions that you need to keep in mind.
为什么直接在style prop里读取元素属性行不通?
When you write something like style={{display: currentElement.backgroundColor === 'red' ? 'inline': 'none'}}, that won't work because during React's JSX rendering phase, currentElement isn't a real DOM element yet. React's style prop is driven by your component's state/data, not by reading live CSS values from the DOM. You can't directly reference an element's actual applied CSS properties in the style prop like that.
两种可行的解决方案
1. 数据驱动(推荐的React方式)
If the background color of your element is controlled by React state (which it should be, whenever possible), you don't need to read the DOM at all. Just use the same state variable to control both the background color and the display property. This is the most "React-native" approach, as it keeps your UI in sync with your component's state.
Example code for a functional component:
import { useState } from 'react'; function DynamicStyleComponent() { // State to control the background color const [bgColor, setBgColor] = useState('red'); return ( <div style={{ backgroundColor: bgColor, // Use the same state to conditionally set display display: bgColor === 'red' ? 'inline' : 'none', padding: '1rem', margin: '1rem' }} onClick={() => setBgColor(bgColor === 'red' ? 'blue' : 'red')} > Click me to toggle color & visibility </div> ); }
This way, you never have to touch the DOM directly—all style logic is tied to your component's state, which avoids inconsistencies between React's virtual DOM and the real DOM.
2. 读取实时DOM样式(当状态无法控制样式时)
If the background color is coming from outside your React component (e.g., external CSS stylesheets, third-party libraries, or direct DOM manipulations), you'll need to use a ref to access the real DOM element, then read its computed styles with window.getComputedStyle(). You can then update your component's state to control the display property.
Example code for a functional component:
import { useState, useRef, useEffect } from 'react'; function DOMDrivenStyleComponent() { const [isDisplayed, setIsDisplayed] = useState(false); // Create a ref to access the DOM element const elementRef = useRef(null); useEffect(() => { const element = elementRef.current; if (element) { // Get the computed styles (includes all applied styles, not just inline) const computedStyle = window.getComputedStyle(element); // Note: getComputedStyle returns colors in RGB/RGBA format, not hex or named colors const bgColor = computedStyle.backgroundColor; // Update state based on the real background color setIsDisplayed(bgColor === 'rgb(255, 0, 0)'); // Matches the named color 'red' } }, []); // Add dependencies here if the background color can change dynamically return ( <div ref={elementRef} // Assume this background color is set by external CSS, not React state className="external-style-class" style={{ display: isDisplayed ? 'inline' : 'none', padding: '1rem', margin: '1rem' }} > My visibility depends on external CSS background color </div> ); }
Important notes for this approach:
getComputedStyle()returns styles in a standardized format (e.g.,rgb(255, 0, 0)instead of'red'), so make sure your condition matches the correct format.- If the background color can change after the component mounts, update the
useEffectdependency array to trigger a re-check when the relevant data changes. - Avoid overusing this approach—React works best when you keep UI logic tied to state instead of reading from the DOM.
Final Takeaway
Whenever possible, use state to drive all your style decisions—it's cleaner, more maintainable, and aligns with React's core principles. Only resort to reading DOM styles when the style in question is outside your component's control.
内容的提问来源于stack exchange,提问作者rasika

