如何在React中获取当前URL并应用到CSS的content属性中?
Absolutely! You can match the exact functionality from your PHP example in React. Let’s break down how to do it—React handles dynamic values differently than server-side PHP, but the end result will be identical.
First, let’s recap what your PHP code does:
It grabs the current page's domain + request URI, plugs it into Google's QR code API, and sets that API URL as the
contentvalue for a CSS class.
Here’s how to replicate this in React:
Step 1: Get the Current Page URL
In React, you can access the current URL using the browser’s window.location object—this replaces PHP’s $_SERVER["SERVER_NAME"] and $_SERVER["REQUEST_URI"]:
window.location.hrefgives you the full URL (equivalent to combining the two PHP variables)- Or, to mirror the PHP structure exactly:
window.location.origin + window.location.pathname + window.location.search
Step 2: Inject the URL into CSS content
Since content is typically used for pseudo-elements (like ::before or ::after), you can’t use inline styles directly. Instead, use one of these two common approaches:
Option 1: Use CSS-in-JS (e.g., styled-components)
If you’re using a CSS-in-JS library like styled-components, you can dynamically pass the QR code URL to your styles:
import styled from 'styled-components'; // Styled component with dynamic pseudo-element content const QrContainer = styled.div` &::before { content: url(${props => `https://chart.googleapis.com/chart?cht=qr&chs=150x150&chl=${encodeURIComponent(props.currentUrl)}&choe=UTF-8`}); } `; function App() { // Get current URL when the component mounts const currentUrl = window.location.href; return ( <QrContainer currentUrl={currentUrl}> {/* Your page content here */} </QrContainer> ); } export default App;
Option 2: Dynamically Generate a Style Tag
If you prefer not to use CSS-in-JS, create a <style> tag dynamically and inject it into the DOM:
import { useEffect } from 'react'; function App() { useEffect(() => { // Fetch and encode the current URL const currentUrl = window.location.href; const encodedUrl = encodeURIComponent(currentUrl); // Build the full QR code API URL const qrCodeUrl = `https://chart.googleapis.com/chart?cht=qr&chs=150x150&chl=${encodedUrl}&choe=UTF-8`; // Create and populate a style element const style = document.createElement('style'); style.textContent = ` .qr-class::before { content: url(${qrCodeUrl}); } `; // Add the style to the document head document.head.appendChild(style); // Clean up the style tag when the component unmounts return () => document.head.removeChild(style); }, []); return ( <div className="qr-class"> {/* Your page content here */} </div> ); } export default App;
Key Notes
- I added
encodeURIComponent()to properly escape the URL for the QR code API—this is a best practice your PHP example missed, and it ensures special characters (like?,&) don’t break the API request. - The
chsparameter in your PHP example was150x15(likely a typo)—I corrected it to150x150for a square QR code, but you can change it back if intentional. - Both approaches will render the QR code exactly like your PHP code does, pulling the current page’s URL dynamically when the component loads.
内容的提问来源于stack exchange,提问作者user1763354

