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

React中实现选中select选项后点击按钮跳转对应value URL的方法

React 实现下拉选项选中后点击跳转的方案

完整实现代码

import { useState } from 'react';

function PurchasePage() {
  // 初始化选中值为第一个option的地址,避免用户未选择直接点击的空值问题
  const [selectedUrl, setSelectedUrl] = useState(
    "https://hosters.pk/clientarea/index.php/store/flash-high-speed/basic-1?=1&billingcycle=monthly"
  );

  const handleJump = () => {
    // 可选:添加地址合法性校验逻辑
    if (!selectedUrl) return;
    // 当前页面跳转用下面这行
    window.location.href = selectedUrl;
    // 如果需要新标签页打开,替换为下面这行
    // window.open(selectedUrl, '_blank');
  };

  return (
    <div>
      <select 
        value={selectedUrl} 
        onChange={(e) => setSelectedUrl(e.target.value)}
      >
        <option value="https://hosters.pk/clientarea/index.php/store/flash-high-speed/basic-1?=1&billingcycle=monthly">option1</option>
        <option value="https://hosters.pk/clientarea/index.php/store/flash-high-speed/unlimited?=1&billingcycle=quarterly">option2</option>
      </select>
      <button onClick={handleJump}>Buy Now</button>
    </div>
  );
}

export default PurchasePage;

核心逻辑说明

  • 采用React受控组件模式管理下拉框的值,不需要手动操作DOM获取选中的option属性
  • onChange事件会实时同步用户选中的地址到状态中
  • 点击按钮时直接读取状态中存储的地址调用浏览器跳转API即可完成需求

可选优化点

  • 可以添加跳转前的确认弹窗,避免用户误触
  • 可以对选中的地址做合法性校验,避免异常地址导致跳转错误

内容的提问来源于stack exchange,提问作者Hayaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:03