簡體   English   中英

React - 在 Button 的 OnClick 滿足某些條件后如何重定向到另一個頁面?

[英]React - How can I redirect to another page after some conditions are met on the OnClick of a Button?

所以在這個組件中,我有一個名為 Submit 的按鈕,單擊它會執行以下操作:它將用戶制作的繪圖導出為 jpeg url,將其傳遞給另一個返回圖像標題的 api,然后比較此圖像之前返回的字符串提示的標題。 我想根據圖像標題和提示之間的比較是否相同將用戶重定向到另一個網頁。 我怎么會go這個呢?

 <button onClick={() => { let W = this.handleWord() let valid = this.state.valid this.canvas.current.exportImage("jpeg").then(imagedata => { fetch('https://hf.space/embed/Salesforce/BLIP/+/api/predict/', { method: "POST", body: JSON.stringify({"data":[imagedata,"Image Captioning","None","Beam Sampling"]}), headers: { "Content-Type": "application/json" } }).then(function(response) { return response.json(); }).then(function(json_response) {blip = json_response.data valid = blip.includes(W) //blip which is a string returned by the api above is checked to see if W is in the string console.log(valid) //based on this valid boolean, i want to have page be redirected to either Success or Share, two seperate pages ive made }) }).catch(e => { console.log(e); }); }} className='buttonprops'> <img src={submitbutton} width = {120} height = {35} alt = 'Submit!' /> </button>

const YourComponent = () => {
  // if you're using react-router...
  const navigate = useNavigate(); // import { useNavigate } from 'react-router-dom'

  const handleClick = () => {
   // your button click logic...
   navigate(valid ? "/success" : "/share")

   // or if you're not using react-router...
   window.location.pathname = valid ? "/success" : "/share"
  }

  return <button onClick={handleClick}>click me</button>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM