我的 React 组件中有这段代码。
我需要的是重用其他文件中的一些组件和功能。
但是有些函数会更新我的状态。
我想知道实现此目标的最佳实践是什么。
MyComponent 主要:
import React, { Component, Fragment } from "react";
import { GenericFunction, GenericComponent } from "./functions.js";
class MyComponent extends Component {
state = {
myValueState: false
};
render() {
const { myValueState } = this.state;
return (
<div>
<GenericComponent
GenericFunction={GenericFunction}
// GenericFunction={GenericFunction.bind(this)} // -----> With this it works good, but is this a best practice?
/>
</div>
);
}
}
export default MyComponent;
functions.js 文件:
export function GenericFunction(items) {
if (items) {
this.setState({ ...this.state, myValueState: true });
} else {
this.setState({ ...this.state, myValueState: false });
}
}
GenericFunction={GenericFunction.bind(this)}
这是一个好方法吗?
我听说过 bind(this)
的问题。我错了吗?
最佳答案
如果您的目的只是绑定(bind)函数,那么您只能在构造函数中执行一次,如下所示
class MyComponent extends Component {
constructor(){
super();
// bind the function only once
this.GenericFunction = GenericFunction.bind(this)
}
state = {
myValueState: false
};
render() {
const { myValueState } = this.state;
return (
<div>
<GenericComponent
GenericFunction={this.GenericFunction} // And use it like this
/>
</div>
);
}
}
关于javascript - ReactJS,Javascript,使用状态更改的导入函数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306851/