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

React实现输入城市名,点击按钮在新标签页打开谷歌地图景点链接

实现目标功能的Destination组件代码

以下是修改后的完整代码,可实现你需要的三个功能:

import React, { useState } from 'react'

const Destination = () => {
  // 用useState管理输入的城市名称
  const [city, setCity] = useState('')

  // 处理搜索按钮点击事件
  const handleSearch = () => {
    if (!city.trim()) return // 空输入不执行操作
    const baseUrl = 'https://www.google.com/maps/search/tourist+places+in+'
    const fullUrl = `${baseUrl}${encodeURIComponent(city)}`
    // 在新标签页打开链接
    window.open(fullUrl, '_blank')
  }

  return (
    <div>
      <h1>Destination</h1> 
      <input 
        type="text" 
        name="place" 
        className="form-control" 
        id="place" 
        placeholder="Enter place"
        value={city}
        onChange={(e) => setCity(e.target.value)}
      />

      <button type="button" onClick={handleSearch}> Search </button>
    </div>
  )
}

export default Destination

关键修改说明:

  • 状态管理:使用useState钩子跟踪输入框内容,确保输入值与组件状态同步。
  • 输入绑定:给input添加value={city}和onChange事件,实时更新state中的城市名称。
  • 类名修正:将原生HTML的class改为React规范的className属性。
  • 点击事件处理:给按钮添加onClick事件触发handleSearch函数:
    • 先判断输入是否为空,避免无效请求;
    • 用encodeURIComponent对城市名称编码,兼容含空格或特殊字符的输入;
    • 通过window.open(fullUrl, '_blank')在新标签页打开拼接好的链接。
  • 按钮类型调整:将按钮type="Submit"改为type="button",避免默认表单提交行为(此处无表单,无需submit类型)。

内容的提问来源于stack exchange,提问作者33_KAWALE SUSHANT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:15:48