簡體   English   中英

當另一個元素有焦點時如何顯示按鈕?

[英]How can I show a button when another element has focus?

我有多行,每行包含兩個文本輸入和一個按鈕。 當用戶專注於其中一個輸入時,應顯示該按鈕。 當元素失去焦點時,按鈕應該再次變得不可見。 我最好的嘗試:

const Input = ({inputRef}) => {
  return (
    <>
      <h1>Input</h1>
      <input type="text" ref={inputRef}/>
    </>
  )
}

export default () => {
  const firstRef = useRef(null);
  const secondRef = useRef(null);
  const it = useRef(null);

  const [editing, setEditing] = useState(false);

  function handleClick(e) {
    firstRef.current.focus();
  }

  function handleSave() {
    console.log("saving!");
  }
  
  function checkFocus(e) {
    if (!it.current.contains(document.activeElement)) {
      setEditing(false);
    } else {
      setEditing(true);
    }
  }

  useEffect(() => {
    document.body.addEventListener("focus", checkFocus, true);

    return () => {
      document.body.removeEventListener("focus", checkFocus, true);
    }
  }, []);

  return (
    <div ref={it}>
      <Input inputRef={firstRef}/>
      <Input inputRef={secondRef}/>

      <button type="button" onClick={handleSave} style={{visibility: editing ? "visible" : "hidden"}}>Save</button>
      <button type="button" onClick={handleClick}>Edit</button>
    </div>
  )
}

有沒有更好/更優雅和有效的方法來實現這一目標?

您可以使用onBluronFocus事件。

這應該按預期工作,只需調整組件上的邏輯

編輯

編輯了 onBlur 方法。

const INITIAL_STATE = {
  input: ''
}

export default function App() {
  const [show, setShow] = useState(false);
  const [value, setValue] = useState(INITIAL_STATE);

  const handleChange = (e) => {
    const { value, name } = e.target;
    setValue(prevState => ({ ...prevState, [name]: value }))
  }

  const onBlur = () => {
    if (!value.input) {
      setShow(false)
    }
  }

  return (
    <>
      <Input name="input" onChange={handleChange} value={value.input} onFocus={() => setShow(true)} onBlur={onBlur} />
      {show && <button>TEST</button>}
    </>
  );
}

const Input = (props) => {
  return (
    <>
      <h1>Input</h1>
      <input {...props} type="text" />
    </>
  );
};

這是您僅使用 CSS 嘗試的解決方案,在我看來,這使它更優雅(並且性能更高,但實際上可以忽略不計)。

https://codepen.io/danny_does_stuff/pen/QWMprMJ

<div>
      <input id="input1" />
      <input id="input2" />

      <button id="save-button">Save</button>
      <button id="edit-button">Edit</button>
</div>

<style>
input#input2:focus + button#save-button {
  visibility: hidden;
}
</style>

如果你想以更 React 的方式來做,你可以按照 Marco B 在他的回答中提出的建議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM