Jd Li Jd Li - 3 months ago 11
React JSX Question

react.js How to change the ball's class every seconds?


  1. I am a beginer to learn react.js. I want to change the ball's class in every seconds?one second is "on",another is "off".

  2. I am try to use
    setInterval
    but there have error
    Error: Invariant Violation: EzLampComp.render(): A valid ReactComponent must be returned.

  3. my code is here. How to solve ??

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://cdn.bootcss.com/react/0.14.1/react.js"></script>
    <script src="http://cdn.bootcss.com/react/0.14.1/react-dom.js"></script>
    <script src="http://cdn.bootcss.com/babel-core/5.8.32/browser.min.js"></script>
    </head>
    <style>
    .ez-lamp{
    display : inline-block;
    margin : 5px;
    width : 30px;
    height : 30px;
    border-radius : 50%;
    }
    .ez-lamp.on{
    opacity : 1;
    background : -webkit-radial-gradient(30% 30%,white 5%,red 95%);
    }
    .ez-lamp.off{
    opacity : 0.5;
    background : -webkit-radial-gradient(30% 30%,#888 5%,red 95%);
    }
    </style>
    <body>
    <div id="content"></div>
    <script type = "text/babel">
    var EzLampComp = React.createClass({
    render : function(){
    var onoff = this.props.onoff;
    setInterval(function(){
    if(onoff="on")
    return <span className = "ez-lamp off"></span>;
    else
    return <span className = "ez-lamp off"></span>;

    },1000);

    // if(onoff == "on")
    // return <span className = "ez-lamp off"></span>; //JSX
    // else
    // return <span className = "ez-lamp on"></span>; //JSX
    }
    });
    ReactDOM.render(
    <EzLampComp onoff="on"/> , //JSX
    document.querySelector("#content"));
    </script>
    </body>
    </html>


    }


Answer

setInterval should be called from componentDidMount and should toggle only the state.

getInitialState() {
  return {
    onoff: this.props.onoff
  }
}

componentDidMount() {
  setInterval(function() {
    this.setState({
      onoff: !this.state.onoff
    }, 1000);
  }
}
Comments