我有一个React组件
export default class Archive extends React.Component {
...
}
componentDidMount
和onClick
方法部分使用相同的代码,但参数略有变化。
是否可以在组件类中创建一个函数,以便可以在组件的范围内重用它?
答案 0 :(得分:65)
您可以在反应组件中创建函数。它实际上是常规的ES6 class,它继承自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" />;
}
}
答案 1 :(得分:15)
另一种方式:
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
答案 2 :(得分:5)
你可以试试这个。
// 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;
你唯一关心的是你必须将上下文绑定到函数
答案 3 :(得分:0)
以React Functional方式
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"));