2016-10-28 27 views
17

我想調用某個嵌入式html中的函數。我嘗試了以下但該函數未被調用。這是在render方法中調用函數的不正確方式嗎?如何調用React/Jsx中的渲染函數

import React, { Component, PropTypes } from 'react'; 

export default class PatientTable extends Component { 
     constructor(props) { 
     super(props); 
     this.state = { 
     checking:false 
     }; 
     this.renderIcon = this.renderIcon.bind(this); 
    } 

    renderIcon(){ 
    console.log("came here") 
    return(
     <div>Function called</div> 
    ) 
    } 

    render() { 

    return (
     <div className="patient-container"> 

     {this.renderIcon}  

     </div> 
    ); 
} 
} 

回答

41

要調用你必須添加()

{this.renderIcon()} 
+0

它取決於您的需要,您可以使用'this.renderIcon()'或綁定'this.renderIcon.bind(this)'。 這是正確的嗎?有人寫下了。 – Siddharth

+4

討厭新事物,失蹤():S 謝謝:) – OmarBizreh

-1

class App extends React.Component { 
 
    
 
    buttonClick(){ 
 
    console.log("came here") 
 
    
 
    } 
 
    
 
    subComponent() { 
 
    return (<div>Hello World</div>); 
 
    } 
 
    
 
    render() { 
 
    return ( 
 
     <div className="patient-container"> 
 
      <button onClick={this.buttonClick.bind(this)}>Click me</button> 
 
      {this.subComponent()} 
 
     </div> 
 
    ) 
 
    } 
 
    
 

 

 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'));
<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>

這取決於你的需要的功能,U可以使用this.renderIcon()bindthis.renderIcon.bind(this)

UPDATE

這就是你如何調用render之外的方法。

buttonClick(){ 
    console.log("came here") 
} 

render() { 
    return (
     <div className="patient-container"> 
      <button onClick={this.buttonClick.bind(this)}>Click me</button> 
     </div> 
    ); 
} 

推薦的方法是編寫一個單獨的組件並導入它。

相關問題