react如何取到当前页面的值
获取当前页面 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 提供的方法。







