当前位置:首页 > React

react如何取到当前页面的值

2026-01-26 04:11:47React

获取当前页面 URL 的值

在 React 中获取当前页面的 URL 可以使用 window.location 对象或 useLocation 钩子(React Router v5+)。以下是两种方法的具体实现:

方法一:使用 window.location

const currentUrl = window.location.href; // 完整 URL
const pathname = window.location.pathname; // 路径部分
const searchParams = new URLSearchParams(window.location.search); // 查询参数
const paramValue = searchParams.get('key'); // 获取特定参数值

方法二:使用 React Router 的 useLocation

import { useLocation } from 'react-router-dom';

function MyComponent() {
  const location = useLocation();
  const currentPath = location.pathname; // 当前路径
  const searchParams = new URLSearchParams(location.search); // 查询参数
  const paramValue = searchParams.get('key'); // 获取参数
  return <div>{currentPath}</div>;
}

获取页面 DOM 元素的值

若需获取页面中特定输入框或元素的值,可通过 useRef 或受控组件实现。

方法一:使用 useRef 获取输入值

import { useRef } from 'react';

function InputComponent() {
  const inputRef = useRef(null);

  const handleClick = () => {
    const value = inputRef.current.value; // 获取输入框的值
    console.log(value);
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>获取值</button>
    </div>
  );
}

方法二:受控组件(推荐)

import { useState } from 'react';

function ControlledInput() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (e) => {
    setInputValue(e.target.value); // 实时更新状态
  };

  return (
    <div>
      <input value={inputValue} onChange={handleChange} />
      <p>当前值: {inputValue}</p>
    </div>
  );
}

获取路由参数的值

若使用 React Router 传递动态路由参数(如 /user/:id),可通过 useParams 获取:

import { useParams } from 'react-router-dom';

function UserProfile() {
  const { id } = useParams(); // 获取路由参数
  return <div>用户ID: {id}</div>;
}

注意事项

  • SSR 兼容性:在服务端渲染(如 Next.js)中,window 对象不存在,需通过 useEffect 或条件渲染避免报错。
  • React Router 版本:v6 与 v5 的 API 略有差异,需根据项目版本调整代码。
  • 安全性:直接操作 window.location 或 DOM 时需注意 XSS 风险,建议优先使用受控组件或 React Router 提供的方法。

react如何取到当前页面的值

标签: 页面react
分享给朋友:

相关文章

电脑如何安装react

电脑如何安装react

安装 Node.js 和 npm React 依赖于 Node.js 和 npm(Node Package Manager)。从 Node.js 官网下载并安装最新稳定版本,安装完成后会自动包含 np…

h5实现页面跳转页面

h5实现页面跳转页面

H5 实现页面跳转的方法 在 H5(HTML5)中,实现页面跳转可以通过多种方式完成,以下是常见的几种方法: 使用 <a> 标签 通过 HTML 的 <a> 标签实现页面跳转…

react如何发音

react如何发音

React的发音 React的正确发音为 /riˈækt/,类似于“ree-akt”。以下是详细说明: 发音分解 第一个音节“Ree”发音类似英文单词“see”中的“ee”音。…

react如何循环

react如何循环

循环渲染列表 在React中循环渲染列表通常使用map方法,这是最常用的方式。通过map可以将数组中的每个元素转换为React元素并渲染到页面上。 const items = ['Apple', '…

react如何发布

react如何发布

发布React应用的步骤 构建生产版本 使用以下命令生成优化后的生产版本代码,代码会被压缩并移除开发环境中的调试工具: npm run build 构建完成后会生成build文件夹,包含所有静态资…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…