将prop传递到React中的父组件时变得不确定

时间:2018-08-07 19:13:33

标签: reactjs react-native

我正在学习反应,我有两个组成部分,Counter.jsxCounters.jsx。我的Counter.jsx中有一个按钮,并且在onDelete函数上设置了一个名为onClick的方法。我仍在处理onDelete代码,但是我想查看单击“删除”时正在删除的按钮。现在,我拥有它,因此当我单击delete button时,它将显示正在删除哪个按钮id。由于某些原因,当我检入chrome控制台时,我总是变得不确定。我将代码放到下面。

class Counters extends Component {
  state = {
    counters: [
      { id: 1, value: 2 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ]
  };

  handleDelete = counterId => {
    console.log("Event handler called", counterId);
  };

  render() {
    return (
      <div>
        {this.state.counters.map(counters => (
          <Counter
            key={counters.id}
            onDelete={this.handleDelete}
            value={counters.value}
          />
        ))}
      </div>
    );
  }
}

class Counter extends Component {
  render() {
    return (
      <button
        onClick={() => this.props.onDelete(this.props.id)}
        className="btn btn-danger btn-sm m-2"
      >
        Delete
      </button>
    );
  }
}

enter image description here

1 个答案:

答案 0 :(得分:2)

您没有将id作为Counter组件的支持。

如果添加的话就可以了。

<Counter
  key={counters.id}
  id={counters.id}
  onDelete={this.handleDelete}
  value={counters.value}
/>

class Counters extends React.Component {
  state = {
    counters: [
      { id: 1, value: 2 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ]
  };

  handleDelete = counterId => {
    this.setState(prevState => ({
      counters: prevState.counters.filter(c => c.id !== counterId)
    }));
  };

  render() {
    return (
      <div>
        {this.state.counters.map(counters => (
          <Counter
            key={counters.id}
            id={counters.id}
            onDelete={this.handleDelete}
            value={counters.value}
          />
        ))}
      </div>
    );
  }
}

class Counter extends React.Component {
  render() {
    return (
      <button
        onClick={() => this.props.onDelete(this.props.id)}
        className="btn btn-danger btn-sm m-2"
      >
        Delete
      </button>
    );
  }
}

ReactDOM.render(<Counters />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>