[英]ReactJS, Javascript, the correct way to use imported functions with State changes
我的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)
有问题。 我错了吗?
如果您的目的是仅绑定函数,则只能在构造函数中进行一次这样的操作
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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.