2017-02-16 24 views

回答

1

檢查這個例子:

比方說你有2個分量App and Child,並希望render子組件上選中複選框,這就是所謂的conditional rendering

app.js文件,導入文件child.jsApp組件:

import Child from './child'; 

class App extends React.Component { 
    constructor() { 
     super(); 
     this.showComments = this.showComments.bind(this); 
     this.state = { 
      showComponent: false, 
     }; 
    } 

    showComments(e) { 
     this.setState({ 
      showComponent: e.target.checked, 
     }); 
    } 

    render() { 
      return (
       <div className="add_checkbox"> 
        <span>Enable Comments</span> 
        <input className="checkbox" type="checkbox" name="enable_comment" onClick={this.showComments} value="enable_comment"/> 
        {this.state.showComponent ? <Child/> : null} 
       </div> 
     ) 
    } 
} 

child.js文件:

export default class Child extends React.Component{ 
    render(){ 
     return(
      <div>Hello</div> 
     ); 
    } 
} 

ReactDOM.render(<App />, document.getElementById('container')); 

檢查fiddle的工作例如:https://jsfiddle.net/ztx9kd1w/

讓我知道你是否 需要幫助嗎。