2016-01-19 46 views
15

我有一个阵营部件创建自定义功能作出反应组分

export default class Archive extends React.Component { 
    ... 
} 

componentDidMountonClick方法部分使用相同的代码,除在参数稍有变化。

是否可以在组件类中创建一个函数,以便它可以在组件的作用域中重用?

回答

35

您可以在反应组件中创建函数。它实际上是从React.Component继承的常规ES6 class。只是要小心,并将其绑定到正确的上下文中onClick事件:

export default class Archive extends React.Component { 

    saySomething(something) { 
     console.log(something); 
    } 

    handleClick(e) { 
     this.saySomething("element clicked"); 
    } 

    componentDidMount() { 
     this.saySomething("component did mount"); 
    } 

    render() { 
     return <button onClick={this.handleClick.bind(this)} value="Click me" />; 
    } 
} 
+0

这么简单...谢谢! – Alexey

+0

欢迎您:-) – madox2

+0

如果您想对函数进行递归调用,该怎么办?你如何在函数中调用它? – Norfeldt

2
you can try this. 

    //Author : Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time) 
import React from 'react'; 
import RippleButton from '../../Components/RippleButton/rippleButton.jsx'; 

class HtmlComponents extends React.Component { 
    constructor(props){ 
     super(props); 
     this.rippleClickFunction=this.rippleClickFunction.bind(this); 
    } 
    rippleClickFunction(){ 
     //do stuff. 
     // foo==bar 
    } 
    render() { 
     return (
     <article> 
      <h1>React Components</h1> 
      <RippleButton onClick={this.rippleClickFunction}/> 
     </article> 
    ); 
    } 
} 

export default HtmlComponents; 

唯一关心的是你有上下文绑定到函数