React:使用多个onClick重复渲染JSX

时间:2017-03-08 14:45:17

标签: html5 reactjs

1 个答案:

答案 0 :(得分:0)

这是一个CodePen来显示它的实际效果

class NewComponent extends React.Component {
  render() {
    return (
      <div {...this.props}>
        new component
      </div>
    );
  }  
}

class Button extends React.Component {
  render() {
    return (
      <button {...this.props}>
        click
      </button>
    );
  }  
}

class App extends React.Component {
  constructor() {
    super();
    
    this.state = {
      clicked: false
    };
    
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    this.setState({
      clicked: true
    });
  }
  
  render() {
    return (
      <div>
        <Button onClick={this.handleClick} />
        {this.state.clicked ? <NewComponent /> : null}
      </div>
    );
  }
};

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">loading...</div>