解决的两种方式:在使用React遇见类型“HTMLElement

2022-06-20  本文已影响0人  一只小小小bunny
  const replayInputRef = useRef(null)
<textarea
className={styles['com-btm-reply-text']}
  id='re_input'
  ref={replayInputRef}
  onKeyDown={replayInputText}
  placeholder="Enter发送,Shift+Enter换行"
  autoComplete="off"
  autoFocus={true} >
</textarea>
// @ts-ignore
  const replayInputText = (e) => {
    const replayInputRefCurrent = replayInputRef.current as unknown as HTMLDivElement as any
    const replayText = replayInputRefCurrent.value//获取输入的值

    // enter回车键判断和shit+enter的判断,因为默认enter有enter+shif的换行功能
    if (!e.shiftKey && e.keyCode === 13) {
      e.cancelBubble = true; //ie阻止冒泡行为
      e.stopPropagation();//Firefox阻止冒泡行为
      e.preventDefault(); //取消事件的默认动作*换行
      setOnEnter('onEnter')//按下回车键onEnter为true
      replayInputRefCurrent.value = ''//Enter之后情况输入的文本
      // 将输入的内容push到指定显示内容的位置
      setList([
        ...list,
        {
          id: list.length + 1,
          useId: 'User_10',
          time: '2022-10-10 08:00:00',
          solve: 'solved',
          content: replayText
        }
      ])
    }
  }

tsx中,如果不使用any的,就用这第二种方式

// @ts-ignore
  const replayInputText = (e) => {
    let replayInputRefCurrent = (document.getElementById('re_input') as HTMLInputElement).value; //获取输入的值
    // enter回车键判断和shit+enter的判断,因为默认enter有enter+shif的换行功能
    if (!e.shiftKey && e.keyCode === 13) {
      e.cancelBubble = true; //ie阻止冒泡行为
      e.stopPropagation();//Firefox阻止冒泡行为
      e.preventDefault(); //取消事件的默认动作*换行
      setOnEnter('onEnter');//按下回车键onEnter为true
      (document.getElementById('re_input') as HTMLInputElement).value = ''
      setList([
        ...list,
        {
          id: list.length + 1,
          useId: 'User_10',
          time: '2022-10-10 08:00:00',
          solve: 'solved',
          content: replayInputRefCurrent
        }
      ])
    }
  }

在TSX中的用法

  const replayInputText = (e: React.KeyboardEvent) => {
    const replayInputRefCurrent = (document.getElementById('re_input') as HTMLInputElement).value
    // enter回车键
    if (!e.shiftKey && e.key === 'Enter') {
      // e.cancelBubble = true //ie阻止冒泡行为,React.KeyboardEvent不支持
      e.stopPropagation() //Firefox阻止冒泡行为
      e.preventDefault() //取消事件的默认动作*换行
      setOnEnter('onEnter') //按下回车键onEnter为true
        ; (document.getElementById('re_input') as HTMLInputElement).value = '' //Enter发送成功后清空value
      setList([
        ...list,
        {
          id: list.length + 1,
          useId: 'User_10',
          time: '2022-10-10 08:00:00',
          solve: 'solved',
          content: replayInputRefCurrent
        }
      ])
    }
  }
上一篇下一篇

猜你喜欢

热点阅读