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

编程入门 行业动态 更新时间:2024-10-25 16:29:38
本文介绍了在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组件中创建自定义函数

本文发布于:2023-07-14 22:10:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   函数   组件   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!