2017-03-08 131 views

回答

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>