You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中onBlur事件里input的event.target.name可取,div为何返回undefined?

为什么contentEditable的div在onBlur事件里拿不到name属性?

这是个挺容易踩的小坑,我来给你讲明白原因和解决办法:

核心原因

HTML里的name属性是专门为表单元素(比如input、textarea、select这类)设计的标准属性,浏览器会把这些元素的name属性挂载到对应的DOM对象上,所以你能直接通过event.target.name拿到值。

但像div这种普通元素,虽然你可以手动给它加上name属性,但它不属于表单元素范畴,浏览器不会把这个属性作为DOM对象的标准属性暴露出来,所以event.target.name自然就是undefined了。

几种可行的解决办法

1. 用data-*自定义属性(推荐,符合HTML规范)

把div的name换成data-name,然后通过dataset来获取:

import React, { Component } from "react";
export default class Editable extends Component {
  constructor(props) {
    super(props);
    // 绑定this指向
    this.handleBlur = this.handleBlur.bind(this);
  }
  handleBlur(event) {
    console.log(event.target.dataset.name); // 这里能拿到值了
  }
  render() {
    return (
      <div>
        <div data-name={this.props.name} contentEditable={true} onBlur={this.handleBlur}>
          {/* 可编辑内容 */}
        </div>
      </div>
    );
  }
}

2. 直接从组件props中获取(更简单可靠)

既然你的div的name值本来就是从props传进来的,完全不用从事件对象里拿,直接在handleBlur里用this.props.name就行:

handleBlur(event) {
  console.log(this.props.name); // 直接用props里的值,更稳妥
}

注意:要确保handleBlur的this指向正确,要么在constructor里bind,要么用箭头函数定义方法。

3. 用getAttribute手动获取(不推荐,不符合规范)

如果一定要保留name属性,也可以通过DOM的getAttribute方法获取:

handleBlur(event) {
  console.log(event.target.getAttribute('name'));
}

不过这种方式不符合HTML自定义属性的规范,不建议在项目里使用。

内容的提问来源于stack exchange,提问作者user1283776

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:21:45