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

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

我的 React 应用程序遇到了一个奇怪的问题,我无法使我的 deleteTime() 功能正常工作。我打算尝试使用 e.target.valuethis.state.times 中删除一个元素,这将是我要删除的 <li>{key}。 value 属性已正确添加到元素中,但我无法访问它。我知道这个问题与 MaterializeCSS 有关,因为如果我将元素从 <i> 更改为 <button> 而没有图标,则代码有效。

基本上有两个组件,主要的 App 将所有道具提供给 RecentTimes 组件,它只显示格式如下的时间列表:00 : 00 . 00

这是 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">close</i>
    console.log(e.target.value); // undefined
  }

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

如果 e.target 显然具有值属性,我不知道为什么 e.target.value 未定义。

这是 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>
    );
  }
}

您需要使用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>
    );
  }
}

使用数据属性

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

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

或者如果浏览器支持dataset

e.target.dataset.value