Render a component multiple times React.js

后端 未结 3 1938
夕颜
夕颜 2021-01-16 11:43

This is a code for a simple counter.

However, when i Render the view i don\'t get any output. Please tell me what is wrong with the code.

The button is press

相关标签:
3条回答
  • 2021-01-16 11:50

    You cannot return more than one elements from the React class. If you have more than one elements wrap them in a single div like

    var MultiButton = React.createClass({
      render : function (){
        return(
          <div>
              <Title incVal={1}/>
              <Title incVal={5}/>
          </div>
        );
      }
    });
    
    0 讨论(0)
  • 2021-01-16 11:53

    From the official documentation.

    <div>
      Here is a list:
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
      </ul>
    </div>
    

    A React component can't return multiple React elements, but a single JSX expression can have multiple children, so if you want a component to render multiple things you can wrap it in a div like this.

    Change from

    var MultiButton = React.createClass(
      {
        render: function () {
          return (
            <Title incVal={1}/>
            <Title incVal={5}/>
          );
        }
      }  
    );
    

    to

    var MultiButton = React.createClass(
      {
        render: function () {
          return (
            <div>
              <Title incVal={1}/>
              <Title incVal={5}/>
            </div>
          );
        }
      }  
    );
    
    0 讨论(0)
  • 2021-01-16 12:03
     var Title = React.createClass({
    
      getInitialState : function(){
        return {count:0};
      },
      increment : function(){
    
        this.setState({count:this.state.count+this.props.incVal});
      },
      render: function() {
        return (
          <div>
            <h1 >Count : {this.state.count}< /h1>
            <button onClick={this.increment.bind(this)} >Increment</button>
          </div>
        );
      }
    });
    
    
    
    
    var MultiButton = React.createClass({
      render : function (){
        return(
          <Title incVal={1}/>
        );
      }
    });
    
    ReactDOM.render( <MultiButton /> ,
      document.getElementById('example')
    );
    
    0 讨论(0)
提交回复
热议问题