在React组件中创建自定义函数 [英] Creating custom function in React component

查看:339
本文介绍了在React组件中创建自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React组件

I have a React component

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

componentDidMount onClick 方法部分使用相同的代码,但参数稍有变化。

componentDidMount and onClick methods partially use the same code, except for slight change in parameters.

是否可以在组件内创建一个函数class,所以它可以在组件的范围内重用?

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

推荐答案

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

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

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" />;
    }
}

这篇关于在React组件中创建自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆