【问题标题】:onFocus and onBlur events for multiple elements多个元素的 onFocus 和 onBlur 事件
【发布时间】:2021-12-22 18:45:32
【问题描述】:

我正在尝试处理 2 个元素的 onFocusonBlur 事件 - inputtextarea 元素。我什至尝试将它实现为与对象的一种状态,但这是不可能的,所以我将它分为两​​种状态。每当我尝试关注 textarea 时,它都会展开,但是,如果我开始关注 input 元素,它会折叠而不是保持展开状态。我该如何实现?

  const [titleFocused, setTitleFocus] = useState(null);
  const [contentFocused, setContentFocus] = useState(null);
  
  function handleFocus(event) {
    const {name} = event.target;

    setTitleFocus(name === 'title' && true);
    setContentFocus(name === 'content' && true);
  }

  function handleUnfocus(event) {
    const {name} = event.target;

    setTitleFocus(name === 'title' && false);
    setContentFocus(name === 'content' && false);
  }

  return (
    <div >
      <form 
          className="create-note">
        {titleFocused || contentFocused && (
          <input
          name="title"
          onChange={handleChange}
          value={note.title}
          placeholder="Title"
          onFocus={handleFocus}
          onBlur={handleUnfocus}
          />)
        }
        <textarea
          name="content"
          onChange={handleChange}
          value={note.content}
          placeholder="Take a note..."
          onFocus={handleFocus}
          onBlur={handleUnfocus}
          rows={titleFocused || contentFocused ? "3" : "1"}
        />
        <Zoom in={titleFocused || contentFocused} appear={true}>
          <Fab onClick={submitNote}>
            <AddIcon fontSize="large" />
          </Fab>
        </Zoom>
      </form>
    </div>
  );

【问题讨论】:

    标签: javascript html css reactjs jsx


    【解决方案1】:

    可能是由事件句柄切换两种状态引起的,即使事件与组件无关。

    这应该可以工作

    function handleFocus(event) {
        const {name} = event.target;
        name === 'title' && setTitleFocus(true);
        name === 'content' && setContentFocus(true);
     }
    
     function handleUnfocus(event) {
        const {name} = event.target;
        name === 'title' && setTitleFocus(false);
        name === 'content' && setContentFocus( false);
     }
    

    【讨论】:

    • 还是不行,我的实现正确吗?我认为问题在于逻辑
    • 通过扩展,你的意思是文本区域获得更多的行,因为这一行:rows={titleFocused ||以内容为中心? “3”:“1”}
    • 或者缩放组件做什么?
    • 是的,扩展文本区域并显示来自 Zoom 材料的标题输入和提交按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2011-03-20
    • 2010-12-03
    • 1970-01-01
    相关资源
    最近更新 更多