在输入组件中击键后失去焦点,但与内联 JSX 一起工作正常

问题描述 投票:0回答:1

嗨,我想构建一个具有多个输入的页面。然而,MyInput 组件在每次击键后都会失去焦点,而内联 JSX 则可以正常工作,如上所述。

MyInput 组件与内联 JSX 基本相同,我不知道为什么它失去焦点。

您可以从thecodesandbox

查看源代码
reactjs focus
1个回答
0
投票
import "./styles.css";
import { useState } from "react";


function MyInput({
  label,
  value,
  onDataChange
}: {
  label: string;
  value: number;
  onDataChange: (type: string, amount: number) => void;
}) {
  const [amount, setAmount] = useState(value);
  return (
    <div>
      <div>Component input: </div>
      <label>{label}: </label>
      <input
        type="number"
        value={amount ?? 0}
        onChange={(e) => {
          const i = parseInt(e.currentTarget.value);
          if (Number.isNaN(i)) return;
          setAmount(i);
          onDataChange("distance", i);
        }}
      />
    </div>
  );
}

export default function App() {
  const [log, setLog] = useState({
    id: "",
    distance: 0,
    duration: 0,
    weight: 0
  });

  function handleLogDataChange(type: string, amount: number) {
    setLog({ ...log, [type]: amount });
  }



  const [distance, setDistance] = useState(log.distance);
  return (
    <div>
      <div>The distance is {log.distance}</div>
      <div>
        <div>Inline input: </div>
        <span>Distance: </span>
        <input
          type="number"
          value={distance ?? 0}
          onChange={(e) => {
            const i = parseInt(e.currentTarget.value);
            if (Number.isNaN(i)) return;
            setDistance(i);
            handleLogDataChange("distance", i);
          }}
        />
      </div>
      <MyInput
        label="Distance"
        value={log.distance}
        onDataChange={handleLogDataChange}
      />
    </div>
  );
}

刚刚从应用程序外部删除了 MyInput。不要在组件内声明组件

© www.soinside.com 2019 - 2024. All rights reserved.