在活动内容状态之间切换

Toggle between active content state

我正在构建一个带有情感的 React 选项卡导航组件。我无法找到可以让我执行以下操作的解决方案:

代码如下: Code

import React, { useState } from "react";
import ReactDOM from "react-dom";
import styled from "@emotion/styled";

import "./styles.css";

const StyledShowButton = styled("button", {
  shouldForwardProp: (prop) => ["active"].indexOf(prop) === -1
})`
  color: ${({ active }) => (active ? "red" : "black")};
`;

function App() {
  const [active, setActive] = useState(0);
  const [showInput, setShowInput] = useState(false);

  const handleInputChange = (e) => {
    if (e.target.value < 1) {
      console.log("Reset Everyting");
    }
  };

  const handleTabClick = (e) => {
    const index = parseInt(e.target.id, 0);
    if (index !== active) {
      setActive(index);
    }

    if (!showInput) {
      setShowInput(!showInput);
    }
  };
  return (
    <div className="App">
      <StyledShowButton
        type="button"
        id={0}
        active={active === 0}
        onClick={handleTabClick}
      >
        First
      </StyledShowButton>

      <StyledShowButton
        type="button"
        id={1}
        active={active === 1}
        onClick={handleTabClick}
      >
        Second
      </StyledShowButton>

      {/* CONTENT */}
      {active === 0 ? (
        <input placeholder="First input" onChange={handleInputChange} />
      ) : (
        <input placeholder="Second input" onChange={handleInputChange} />
      )}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

就问我是不是说的不够清楚,

谢谢!

埃里克

您可以先通过为活动状态分配一个空值来以这种方式隐藏输入。 也可以从1开始初始化值,这样id和state状态就不会混淆了。 我做了安排。 您可以查看下面的代码。

您也可以从这里查看link。 Code:

function App() {
  const [active, setActive] = useState(null);
  const [showInput, setShowInput] = useState(false);

  const handleInputChange = (e) => {
    if (e.target.value < 1) {
      setActive(null);
    }
  };

  const handleTabClick = (e) => {
    const index = parseInt(e.target.id, 0);
    if (index !== active) {
      setActive(index);
    }
    if (!showInput) {
      setShowInput(!showInput);
    }
  };

  return (
    <div className="App">
      <StyledShowButton
        type="button"
        id={1}
        active={active === 1}
        onClick={handleTabClick}
      >
        First
      </StyledShowButton>
      <StyledShowButton
        type="button"
        id={2}
        active={active === 2}
        onClick={handleTabClick}
      >
        Second
      </StyledShowButton>
      {/* CONTENT */}
      {active &&
        (active === 1 ? (
          <>
            <input placeholder="First input" onChange={handleInputChange} />
          </>
        ) : (
          <input placeholder="Second input" onChange={handleInputChange} />
        ))}
    </div>
  );
}