繁体   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