Render a component multiple times React.js

2020-03-31 03:32发布

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 pressed and a counter is incremented and is rendered onto the screen.

 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} >Increment</button>
      </div>
    );
  }
});




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

ReactDOM.render( <MultiButton /> ,
  document.getElementById('example')
);

标签: reactjs web
3条回答
家丑人穷心不美
2楼-- · 2020-03-31 04:14

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>
    );
  }
});
查看更多
一夜七次
3楼-- · 2020-03-31 04:17

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>
      );
    }
  }  
);
查看更多
走好不送
4楼-- · 2020-03-31 04:19
 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')
);
查看更多
登录 后发表回答