本文介绍了在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组件中创建自定义函数
发布评论