Javascript 在 React 组件中创建自定义函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34875557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:59:40  来源:igfitidea点击:

Creating custom function in React component

javascriptreactjs

提问by Alexey

I have a React component

我有一个 React 组件

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

componentDidMountand onClickmethods partially use the same code, except for slight change in parameters.

componentDidMountonClick方法部分使用相同的代码,只是参数略有变化。

Is it possible to create a function inside the component class so it can be reused in the scope of the component?

是否可以在组件类中创建一个函数,以便它可以在组件范围内重用?

回答by madox2

You can create functions in react components. It is actually regular ES6 classwhich inherits from React.Component. Just be careful and bind it to the correct context in onClickevent:

您可以在 React 组件中创建函数。它实际上是有规律的ES6类从继承React.Component。请小心并将其绑定到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" />;
    }
}

回答by yiwen

Another way:

其它的办法:

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} value="Click me" />;
  }
}

In this format you don't need to use bind

在这种格式中,您不需要使用 bind

回答by hannad rehman

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;

Yhe only concern is you have to bind the context to the function

你唯一关心的是你必须将上下文绑定到函数