无法在反应组件中看到增量按钮

时间:2018-08-09 14:42:31

标签: reactjs react-native

我有两个componenet,countercounters。当您单击未显示的increment组件中的counter按钮时,我有一个框显示值。我重构了代码,以使我的counter组件是controlled组件而不是uncontrolled组件,以便它从我的props对象获取数据。我将代码粘贴到下面。

更新:我现在可以看到具有增量数量的框,但是当我单击Increment时,会在框中显示Nan作为值。

counter component

import React, { Component } from "react";

class Counter extends Component {
// styles for our bootstrap
  styles = {
fontSize: 30,
fontWeight: "bold"
 };

 render() {
  console.log("props", this.props);
   return (
  <div>
    <span className={this.getBadgeColor()}>{this.formatCount()} 
    </span>
    <button
      onClick={() => this.props.onIncrement(this.props.counter)}
      className="btn btn-secondary btn-md"
    >
      Increment
    </button>

    <button
      onClick={() => this.props.onDelete(this.props.counter.id)}
      className="btn btn-danger btn-sm m-2"
    >
      Delete
    </button>
  </div>
   );
  }

getBadgeColor() {
let classes = "badge m-2 badge-";
classes += this.props.counter.value === 0 ? "warning" : 
"primary";
return classes;
 }

  formatCount() {
  const { value } = this.props.counter;
  return value === 0 ? <h2> Zero </h2> : value;
  }
}

export default Counter;

counters component

import React, { Component } from "react";
import Counter from "./counter";

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

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

 handleReset = () => {
  const counters = this.state.counters.map(c => {
  c.value = 0;
  return c;
   });
   this.setState.counters = { counters };
  };

handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counters };
counters[index].value++;
this.setState({ counters });
  };

  render() {
    return (
      <div>
        <button
      onClick={this.handleReset}
      className="btn btn-primary btn-sm m-2"
    >
      Reset
    </button>

    {this.state.counters.map(counters => (
      <Counter
        key={counters.id}
        onDelete={this.handleDelete}
        counter={counters}
        onIncrement={this.handleIncrement}
      />
    ))}
  </div>
    );
  }
}

export default Counters;

1 个答案:

答案 0 :(得分:0)

您看到的是NaN,因为您应该在counters组件中分配state的值。