简体   繁体   中英

React.js won't render in my Codepen

I'm trying to create a counter and I can't get what's in the render to show on the page.

Here is my code in JS from Codepen (with React and ReactDOM added in external JS)

class Counter extends React.Component {
  constructor() {
    super();
    this.state = {
    };
    this.flash = "";
    this.count = 0;
  }

  componentWillReceiveProps(nextProps) {
    var newValue = nextProps.count;
    if (this.count !== newValue) {
      this.flash = this.flash === "flash1" ? "flash2" : "flash1";
    }
  }

  render () {
    return (
      <div id="counter">
        <button>+</button>
        <button>-</button>
        <div id="count" className={this.flash}>
          {this.count}
        </div>
      </div>
    );
  };
}


ReactDOM.render(<Counter />, document.getElementById('countContainer'));

I can see in my JS code that normally the should be the color brown in my Codepen, so I'm obviously missing something (it's currently yellow).

In my HTML I have the following

<div id="countContainer">
</div>

Note: I'm not done with the code in regards to what it should be able to do in the end. I figured I should try and get it to render on the page before I continue.

My codepen is: URL

I tried this and got an error at the line where the first JSX tag is inside render(). I fixed it by adding the Babel preprocessor in addition to React and ReactDOM.

You can try this code to get the counter working with both increment and decrement count .

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count :0
    };
    this.increment=this.increment.bind(this);
    this.decrement=this.decrement.bind(this);
  }
increment(){
  this.setState({count:this.state.count+1});
}
decrement(){
  this.setState({count:this.state.count-1});
}
  render () {
    return (
      <div id="counter">
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <div>
          {this.state.count}
        </div>
      </div>
    );
  }
}


ReactDOM.render(<Counter />, document.getElementById('countContainer'));

just define the functions and trigger them using onClick().

Here is the working counter in codepen with your code, modified it a bit to make it work. https://codepen.io/coderakki/pen/QOQqMP?editors=0010

Update : also, you need to define count within the state of your component .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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