axios 获取用户输入并单击按钮,它应根据react js中新选项卡中的输入加载url

2hh7jdfx  于 2022-11-23  发布在  iOS
关注(0)|答案(2)|浏览(136)

我想把城市名称作为输入,点击按钮时,它应该调用特定的url https://www.google.com/maps/search/tourist+places+in+孟买,结束url,在react中输入值。它应该在新选项卡中打开url
目标.jsx(文件名)

import React from 'react'

const Destination = () => {
  
  return (
    <div>
     <h1>Destination</h1> 
     <input type="text" name="place" class="form-control" id="place" placeholder="Enter place" />

     <button type="Submit" id="submit"> Search </button>
    </div>

  )
}

export default Destination
iyfjxgzm

iyfjxgzm1#

你可以这样做来搜索新标签中的地方。

import React from 'react';

const Destination = () => {
  const handleSearch = (e) => {
    window.open(
      `https://www.google.com/maps/search/tourist+places+in+${e.target.place.value}`,
      '_blank'
    );
  };

  return (
    <div>
      <h1>Destination</h1>
      <form onSubmit={handleSearch}>
        <input
          type="text"
          name="place"
          class="form-control"
          id="place"
          placeholder="Enter place"
        />

        <button type="Submit" id="submit">
          Search
        </button>
      </form>
    </div>
  );
};

export default Destination;
35g0bw71

35g0bw712#

创建状态:

const [destination, setDestination] = useState("");

然后使用此状态填充搜索查询,如下所示:

<input type="text" name="place" class="form-control" id="place" placeholder="Enter place" value={destination} onChange={(e) => setDesitnation(e.target.value)} />

然后在提交时可以调用按钮onClick()上的自定义函数:

<button id="submit" onClick={searchDestination}> Search </button>

该函数可能如下所示:

const searchDestination = () => {
    window.location.href = `https://www.google.com/maps/search/tourist+places+in+${destination}`;
}

相关问题