外部化各种反应组件中的常用功能 [英] Externalise common functions in various react components
问题描述
在不同的 components
中,我在样式或其他方面使用相同的功能.其中一些函数使用 this.setState({...});
我想将所有这些函数收集在一个共同的地方,所以在重写它们时我不必在所有的地方重写它们组件,但仅限于一个文件.但是,我不知道如何在不丢失上下文的情况下在函数中编写 this.setState({...});
.有办法吗?
In different components
where I use the same functions when it comes to styling or something else. Some of these functions use this.setState({...});
I want to collect all these functions in a common place, so when rewriting them I don't have to rewrite them in all the components, but only on one file. However, I do not know how to write the this.setState({...});
in the functions without loosing its context. Is there a way?
推荐答案
我假设您的意思是导出一个函数并在各个组件中调用此函数,同时保留 this
的范围
I assume you mean exporting one function and call this function in various components while remaining the scope of this
MyExportedFunctions.js:
MyExportedFunctions.js:
export function handleChange(value, {target: {name, type}}) {
this.setState({[name]: value}, () => console.log(this.state));
}
MyComponent.js:
MyComponent.js:
import {handleChange} from "./MyExportedFunctions";
class MyComponent extends Component {
constructor(props) {
super(props);
this.handleChange = handleChange.bind(this);
this.state = {
};
}
...
}
你的意思是这样吗?
这篇关于外部化各种反应组件中的常用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!