You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中获取当前URL并应用到CSS的content属性中?

Replicating PHP QR Code CSS Content in React

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 content value 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.href gives 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 chs parameter in your PHP example was 150x15 (likely a typo)—I corrected it to 150x150 for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:19:12