简体   繁体   English

e.target可以访问,但是e.target.value不在React组件中

[英]e.target is accessible, but e.target.value is not in React component

I'm having a strange issue with my React app where I can't get my deleteTime() function to work. 我的React应用出现一个奇怪的问题,使我的deleteTime()函数无法正常工作。 I was going to try to remove an element from this.state.times by using e.target.value which would be the {key} for the <li> I want to remove. 我打算尝试使用e.target.valuethis.state.times删除一个元素,该元素将是我要删除的<li>{key} The value attribute is getting correctly added to the element, but I just can't access it. value属性已正确添加到元素中,但我无法访问它。 I know for a fact that the problem has to do with MaterializeCSS because if I change the element from an <i> to a <button> without the icons stuff, the code works. 我知道这个问题与MaterializeCSS有关,因为如果我在没有图标内容的情况下将元素从<i>更改为<button> ,则代码可以正常工作。

There are basically two components, the main App which gives all the props to the RecentTimes component which just displays a list of times that are formatted like this: 00 : 00 . 00 基本上有两个组件,主App将所有道具提供给RecentTimes组件,该组件仅显示格式如下的时间列表: 00 : 00 . 00 00 : 00 . 00

Here is what the App component looks like (I removed all the irrelevant stuff): 这是App组件的外观(我删除了所有不相关的内容):

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      times: []
    };
  }

  deleteTime(e) {
    console.log(e.target); // <i value="1" class="material-icons right" data-reactid=".0.0.2.0.0.2:$1.1">close</i>
    console.log(e.target.value); // undefined
  }

  render() {
    return (
      <RecentTimes
        times={this.state.times}
        deleteTime={this.deleteTime}
      />
    );
  }
}

I have no idea why e.target.value is undefined if e.target clearly has a value attribute. 我不知道为什么e.target.value如果未定义e.target显然有值的属性。

And here is the component for the RecentTimes: 这是最近时间的组件:

class RecentTimes extends React.Component {
  render() {
    let icons = 'material-icons right';

    let times = this.props.times.map((time, timeIndex) => {
      return (
        <li key={timeIndex}>
          {time}
          <i value={timeIndex} onClick={this.props.deleteTime} className={icons}>close</i>
        </li>
      );
    });

    return (
      <ul>{times}</ul>
    );
  }
}

Use a data attribute 使用数据属性

<i data-value={timeIndex} onClick={this.props.deleteTime} className={icons}>close</i>

and

e.target.getAttribute('data-value');

or if the browser supports dataset 或者浏览器支持数据集

e.target.dataset.value

You need to use e.target.id. 您需要使用e.target.id。

 class RecentTimes extends React.Component { render() { let icons = 'material-icons right'; let times = this.props.times.map((time, timeIndex) => { return ( <li key={timeIndex}> {time} <i id={timeIndex} onClick={this.props.deleteTime} className={icons}>close</i> </li> ); }); return ( <ul>{times}</ul> ); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM