【问题标题】:get value from onInput event for cotentEditable in React从 onInput 事件中获取 React 中 cotentEditable 的值
【发布时间】:2019-10-28 07:32:28
【问题描述】:

我有一个 contentEditable 标头,我想在其中获取 onInput 事件的值。到目前为止,我已经设法获得了event.target,但它返回了整个 DOM 节点。我只想获取标题的实际值。非常感谢有用的想法。

到目前为止我所尝试的:

  1. console.log(e.target.value) --> 返回undefined

  2. console.log(e.target) --> 返回节点<h5 contenteditable="true" style="margin: 0px;">Lesson 1</h5>

  3. 我也想过将节点转换为字符串并使用reg ex提取值,但是当console.log(e.target.toString())返回[object HTMLHeadingElement]时我不得不放弃了

<h5 contentEditable style={{ margin: 0 }} onInput={e => {
          props.onChangeName(e.target.value)
          console.log(e.target)
      }}>
        {props.name}
</h5>

【问题讨论】:

  • console.log(e.target.textContent)?

标签: javascript reactjs dom-events contenteditable


【解决方案1】:

使用.value 仅适用于表单 html 组件。使用contentEditable 允许您编辑标记的innerHtml。要访问实际内容,您可以运行:

<h5 contentEditable style={{ margin: 0 }} onInput={e => {
      props.onChangeName(e.target.innerHTML);
      //or
      props.onChangeName(e.target.textContent);
  }}>
  {props.name}
</h5>

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多