2016-10-28 17 views
17

Chcę wywołać funkcję wewnątrz osadzonego html. Próbowałem następujące, ale funkcja nie jest wywoływana. Czy byłby to niewłaściwy sposób wywoływania funkcji wewnątrz metody renderowania?Jak wywołać funkcję wewnątrz renderowania w 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> 
    ); 
} 
} 

Odpowiedz

41

Aby wywołać funkcję trzeba dodać ()

{this.renderIcon()} 
+0

To zależy od twoich potrzeb, możesz użyć 'this.renderIcon()' lub powiązać 'this.renderIcon.bind (this)'. czy to prawda? ktoś napisał to poniżej. – Siddharth

+4

Nienawidzę być nowym, brakowało(): S Dzięki :) – 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>

To zależy od potrzeb, można korzystać zarówno this.renderIcon() lub bindthis.renderIcon.bind(this)

UPDATE

W ten sposób wywołuje się metodę poza renderowaniem.

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

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

Zalecanym sposobem jest napisanie oddzielnego komponentu i zaimportowanie go.

Powiązane problemy