反应水平渲染而不是垂直渲染的组件

时间:2019-12-10 23:01:38

标签: javascript html css reactjs jsx

我正在尝试使用counter组件动态渲染计数器数组,但是它们是水平渲染的,我需要垂直渲染它们。

我正在关注codewithmosh.com上的react教程。 我遵循了所有说明,并无数次地遍历了代码。我还想指出,讲师正在使用旧版本的react和bootstrap

counter.jsx

import React, { Component } from "react";

class Counter extends Component {
  state = {
    count: this.props.value
  };

  handleIncriment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <React.Fragment>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={this.handleIncriment}
          className="btn btn-secondary btn-sm"
        >
          Incriment
        </button>
      </React.Fragment>
    );
  }

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "zero" : count;
  }
}

export default Counter;

Counters.jsx


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

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

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

export default Counters;

1 个答案:

答案 0 :(得分:0)

如果在div内使用Fragment而不是Counter,则计数器将是块元素,并且将垂直显示。