如何防止Link弄乱我的单选按钮行为?

我正在尝试构建一个菜单,该菜单以粗体显示当前页面。 为此,我使用单选按钮,以便菜单上的每个项目都是该单选按钮的标签,并且在CSS中,我将活动项目设置为粗体。

My problem is, that because the label is wrapped in a Link element, when an item is clicked nothing really changes. It navigates properly but the radio button sate doesn't change. Maybe everything just re renders ignoring my action? It works just fine without the link element. Why is that? And what can I do to make it work?

这是我的菜单组件的代码:

import "./styles.scss";
import React from "react";
import { Link } from "react-router-dom";

const Menu = () => {

  const turnToLowerCaseWithHyphen = string => {
    return (string[0].toLowerCase() + string.slice(1)).replace(" ", "-");
  };

  const renderMenuItems = array => {
    return array.map(item => {
      const smallHyphenedItem = turnToLowerCaseWithHyphen(item);
      return (
        <div className="flex-group" key={smallHyphenedItem}>
          <input
            className="menu-item__radio"
            id={smallHyphenedItem}
            type="radio"
            name="menu-items"
            onChange={() => console.log(smallHyphenedItem)}
          />
          <Link
            to={"/" + smallHyphenedItem}
            className="menu-item"
            key={smallHyphenedItem}
          >
            <label htmlFor={smallHyphenedItem} className="menu-item__label">
              {item}
            </label>
          </Link>
        </div>
      );
    });
  };

  return (
    <div className="menu">
      {renderMenuItems(["Feed", "Search", "Contact us"])}

    </div>
  );
};

export default Menu;

编辑:我试图在菜单组件中使用一种状态,但没有帮助:

const Menu = () => {
  const [currentPage, setCurrentPage] = useState(null);

  const turnToLowerCaseWithHyphen = string => {
    return (string[0].toLowerCase() + string.slice(1)).replace(" ", "-");
  };

  const renderMenuItems = array => {
    return array.map(item => {
      const smallHyphenedItem = turnToLowerCaseWithHyphen(item);
      return (
        <div className="flex-group" key={smallHyphenedItem}>
          <input
            className="menu-item__radio"
            id={smallHyphenedItem}
            type="radio"
            name="menu-items"
            checked={currentPage === smallHyphenedItem}
            onChange={() => setCurrentPage(smallHyphenedItem)}
          />
          <label htmlFor={smallHyphenedItem} className="menu-item__label">
            <Link
              to={"/" + smallHyphenedItem}
              className="menu-item"
              key={smallHyphenedItem}
            >
              {item}
            </Link>
          </label>
        </div>
      );
    });
  };


  return (
    <div className="menu">
      {renderMenuItems(["Feed", "Search", "Contact us"])}
    </div>
  );
};

export default Menu;
评论