0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ReactでInputとOKボタンを使った編集可能なテキストを作成する

Last updated at Posted at 2024-05-16

まずはInputを使って、InputFormを作ります。
InputFormInputと一つのOKボタンが含まれています。
Inputの値がtmpInputValueに保存されてます。
OKボタンを押すと、valueの値がtmpInputValueに更新されます。
OKボタンを押さなくて、別の所をクリックすると、valueの値が更新されません。

const OKButton = () => (
    <button
      className="m-2"
      type="submit"
      onMouseDown={(e) => {
        setValue(inputTmpValue);
      }}
    >
      
    </button>
  );

const InputForm = ({ isInput, text }: { isInput: boolean; text: string; }) => {
    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
      if (isInput && inputRef.current) {
        inputRef.current.focus();
      }
    }, [isInput]);
    return (
      <form
        style={{ display: isInput ? "block" : "none" }}
        className="border-collapse"
        action={() => { console.log("action"); }}
        onBlur={(e) => {
          setIsInput(!isInput);
          setInputTmpValue(value);
        }}
      >
        <input
          className="border-2"
          type="text"
          name="input"
          value={inputTmpValue}
          onChange={(e) => {
            setInputTmpValue(e.target.value);
          }}
          ref={inputRef}
        />
        <OKButton />
      </form>
    );
  };

次に、Valueを表示するのSpanを作ります。
Spanをクリックすると、Spanが消えて、InputFormが現れます。
その状態はisInputに保存します。

const Span = ({ isInput, text }: { isInput: boolean, text: string; }) => (
    <span
      style={{ display: !isInput ? "block" : "none" }}
      className=" border-red-300 border-2 min-h-4"
      onClick={() => setIsInput(!isInput)}
    >
      {text}
    </span>
  );

最後に、これらをまとめます。

export default function Block() {
  const [value, setValue] = useState("");
  const [inputTmpValue, setInputTmpValue] = useState(value);
  const [isInput, setIsInput] = useState(false);

  const OKButton = () => (
    ...
  );

  const Span = ({ isInput, text }: { isInput: boolean, text: string; }) => (
    ...
  );
  const InputForm = ({ isInput, text }: { isInput: boolean; text: string; }) => {
    ...
  };

  return (
    <div>
      <Span isInput={isInput} text={value} />
      <InputForm isInput={isInput} text={value} />
    </div>
  );

}

出来上がりです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?