2016-01-19 11 views
15

に反応します。は私が</p> <pre><code>export default class Archive extends React.Component { ... } </code></pre> <p><code>componentDidMount</code>と<code>onClick</code>方法は、部分的にパラメータのわずかな変化を除いて、同じコードを使用するコンポーネントに反応しているコンポーネント

コンポーネントのスコープ内で再利用できるように、コンポーネントクラス内で関数を作成することはできますか?

答えて

35

反応コンポーネントで関数を作成できます。実際にはを継承する通常の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; 

唯一の懸念は、ありがとう...あなたはそう簡単な関数

関連する問題

 関連する問題