2016-12-01 62 views

回答

0

ReactDOM.render()返回值實際上是組件的安裝實例:

class Counter extends React.Component { 
 
    
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     count: 0 
 
    }; 
 
    } 
 
    
 
    inc() { 
 
    this.setState({count: this.state.count + 1}); 
 
    } 
 
    
 
    render() { 
 
    return (
 
     <div> 
 
      Count: {this.state.count} 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
const instance = ReactDOM.render(
 
    <Counter />, 
 
    document.getElementById('app') 
 
); 
 

 
instance.inc();
<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="app"></div>

如果您需要訪問深度嵌套的組件,這是一個有點難度,但這應該讓你開始。

+0

謝謝,但我需要能夠在任何地方調用組件方法 – Enda