20
11

Enter押下と日本語IMEの不愉快な関係を解消する

Last updated at Posted at 2024-09-03

この世界は「Enter」を押して確定するテキストフィールドで溢れています。そしてその多くが、日本語IMEの部分確定のために押し下げられたEnterを誤認して、入力中のテキストを確定してしまいます。
今日私は、Reactで作っているアプリで同じ目に遭い、(GPTに聞いて)解消することができました。

特に難しいことも新しいこともしていません。Composing中はEnterを無視しているだけです。

import React, { useState } from "react";
const [isComposing, setIsComposing] = React.useState(false);

const TreeView: React.FC<TreeViewProps> = ({
  const handleKeyDown = (event: {
    stopPropagation: () => void;
    key: string;
  }) => {
    event.stopPropagation();
    if (event.key === "Enter") {
      // If IME is acrive, Enther must be ignored
      if (!isComposing) {
        if (!isEditing) {
          // Editing
          setIsEditing(true);
        } else {
          // Fixing
          handleBlur();
        }
      }
    }
  };

  const handleCompositionStart = () => {
    setIsComposing(true);
  };

  const handleCompositionEnd = () => {
    setIsComposing(false);
  };
  return (
    <input
    type="text"
    value={editValue}
    onChange={handleChange}
    onKeyDown={handleKeyDown}
    onCompositionStart={handleCompositionStart}
    onCompositionEnd={handleCompositionEnd}
    onBlur={handleBlur}
    className="item-name-input"
    />
  )

おそらく、このエントリーをご覧の皆さんの多くはご存知のことでしょう。
私がこのエントリーを書いた理由は、IMEに馴染みのないエンジニアが書いたコードへの改善要求のためです。

Enter押下で確定するコードを書いているときに、「こうやってOnCompositeで処理してください」とお願いすると幸せになれるかもしれません。

20
11
1

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
20
11