2016-12-01 61 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