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

我有一个反应元件

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

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

是否可以在组件类中创建一个函数,以便在组件的作用域中重用它?

174274 次浏览

您可以在反应组件中创建函数。它实际上是从 React.Component继承的常规 ES6课程。在 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" />;
}
}

你可以试试这个。

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

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

另一种方式:

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

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

用反应函数法

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";


const App = () => {
const saySomething = (something) => {
console.log(something);
};
useEffect(() => {
saySomething("from useEffect");
});
const handleClick = (e) => {
saySomething("element clicked");
};
return (
<Button variant="contained" color="primary" onClick={handleClick}>
Hello World
</Button>
);
};


ReactDOM.render(<App />, document.querySelector("#app"));

Https://codesandbox.io/s/currying-meadow-gm9g0