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
相关产品推荐
相关产品推荐

