2017-08-24 60 views
4

这是我的阵营组成:如何使这个里面提供渲染功能

constructor(props) { 
    super(props); 

    this.state = { 
    }; 
    this.showChart = this.showChart.bind(this) 
} 

showChart() { 
    console.log('test') 
} 

render() { 

    {this.showChart} //throws error that, this is undefined 

    return() (
     {this.showChart} //prints test 
    ) 
} 

现在,如果我想从render()调用函数,但外界return()我应该怎么办?

回答

5

您的组件语法在一些地方不正确。渲染中可用this

constructor(props) { 
    super(props); 

    this.state = { 
    }; 
    this.showChart = this.showChart.bind(this) 
} 

showChart() { 
    console.log('test') 
} 

render() { 

    this.showChart() 

    return ( 
     <div>{this.showChart()}</div> 
) 

} 

编辑:

您也可以用箭头功能结合工作职能说你的组件。通过这样做,您不必为bind每个功能。它看起来会更加清晰:

constructor(props) { 
    super(props); 

    this.state = { 
    }; 
} 

showChart =() => { 
    console.log('test') 
} 

render() { 

    this.showChart() 

    return ( 
     <div>{this.showChart()}</div> 
) 

} 
+0

是的你是对的 –

+0

幸福,它帮助你 –

0

替换{} this.showChart与this.showChart()渲染函数内。所以你的新代码应该是

render(){ 
this.showChart(); 

return(
     {this.showChart}  
); 
}