【问题标题】:re-direct to new page on button click in React js在 React js 中单击按钮时重定向到新页面
【发布时间】:2021-11-23 04:38:51
【问题描述】:

我们可以在reactjs中使用<a>标签来重定向到一个页面
目前,我已将其用于链接,但由于某种原因,它无法正常工作

另外,我使用Link Route useHistory 进行重定向,甚至它们都不起作用

我在表格中添加了一个button,我希望在点击时将redirect 添加到新页面

useHistory 我已将其导入到我的 js 文件中

import { useHistory } from "react-router-dom";

我在我的export function 中使用过它

let history = useHistory();
  function handleClick() {
    history.push("/bookingSlot");
  }

button中使用handleClick()

 <button type="button" onClick={handleClick}>
    Click Me!
 </button>

代码片段

import React from 'react';
import '../scss/components/table';
import data from '../../public/userData';
import { useHistory } from "react-router-dom";

export default function ReservedListView() {
  console.log('data :' + JSON.stringify(data));
  let header = Object.keys(data[0]);
  console.log('header :' + header);

  let history = useHistory();

  function handleClick() {
    history.push("/bookingSlot");
  }

  return (
    <div>
      <table id="students" class="table">
        <tbody>
          <tr>
            <th>Name</th>
            <th>Date</th>
            <th>Day</th>
            <th>SimeSlot</th>
          </tr>
          {data.map((el, index) => (
            <tr>
              <td>{el.name}</td>
              <td>{el.date}</td>
              <td>{el.day}</td>
              <td>{el.timeSlot}</td>
            </tr>
          ))}
          <tr>
            <td colSpan="4"> 
            {/* buttons with usehistory()*/}
              <button type="button" onClick={handleClick}>
                Click Me Button!
              </button>

            {/* button with <a> tag */}
              <a href="/bookingSlot.js">Click Me!</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

当我在clickfirst button 我收到此错误

如果我做错了,请告诉我

【问题讨论】:

    标签: reactjs redirect button


    【解决方案1】:

    根据您当前的代码,事情应该可以正常工作,检查这个code sandbox 它可能会有所帮助。

    【讨论】:

    • 谢谢!为此,将查看并找出我的代码的实际问题
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 2021-05-15
    • 2016-07-12
    • 2021-09-07
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多