最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Event target's name is undefined if not an input - Stack Overflow

programmeradmin0浏览0评论

I have this ponent:

...

onInputChange = evt => {
  const target = evt.target;
  let value = null;
  if (target.nodeName === "INPUT")
    value = target.value; //works well
  else if (target.nodeName === "SPAN")
    value = target.innerText; //works well
  const name = target.name; //works well if it's the input, doesn't if it's the span
  this.setState({[name]: value});
}

render() {
  ...
  <input name="myFirstValue" onChange={onInputChange} />
  <span name="mySecondValue" contentEditable="true" onInput={onInputChange}></span>
  ...
}

...

When it's the input that triggers the event, it works well. But the problem is when it's the span: target.name returns undefined and not 'mySecondValue'.

Is this a bug from React? If so, is there a workaround?

Thank you for your help.

I have this ponent:

...

onInputChange = evt => {
  const target = evt.target;
  let value = null;
  if (target.nodeName === "INPUT")
    value = target.value; //works well
  else if (target.nodeName === "SPAN")
    value = target.innerText; //works well
  const name = target.name; //works well if it's the input, doesn't if it's the span
  this.setState({[name]: value});
}

render() {
  ...
  <input name="myFirstValue" onChange={onInputChange} />
  <span name="mySecondValue" contentEditable="true" onInput={onInputChange}></span>
  ...
}

...

When it's the input that triggers the event, it works well. But the problem is when it's the span: target.name returns undefined and not 'mySecondValue'.

Is this a bug from React? If so, is there a workaround?

Thank you for your help.

Share Improve this question asked Feb 18, 2019 at 3:30 JacopoStanchiJacopoStanchi 2,1465 gold badges40 silver badges70 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can put a "name" attribute on any element you want, but only <form> "interactive" elements have DOM APIs that allow you to treat it as a gettable/settable property on the DOM node. Otherwise, you have to use .getAttribute() and .setAttribute() (which should work for <input> etc too).

Thus

const name = target.getAttribute("name");

or maybe

const name = target.name || target.getAttribute("name");

event.target.name works when the event is fired on any element that has a name attribute.

<input
type="text"
id="nume"
**name="lastName"**
class="form-control"
placeholder="Nume"
required
autoFocus
defaultValue={employeeData.lastName || ""}
onChange={handleChange}
/>
发布评论

评论列表(0)

  1. 暂无评论