所以,例如我的代码看起来像这样:
class DoSomething extends Component{
function1(var1, var2){
return var1 * var2 / this.props.var3
}
render(){
<div>{function1(10, 20)}</div>
}
}
我想将function1抽象到自己的文件中并导入它但我仍然希望它可以访问这个组件的(或redux的)props / state。
实现这一目标的最佳方法是什么?对不起,如果这个问题真的很狡猾,那么。
用于演示目的的非反应示例
const func1 = function(var1, var2) {
return var1 * var2 / this.props.var3
}
class DoSomething {
constructor() {
//fake props for demo, wouldn't need this in React Component
this.props = {var3: 3};
// assign an internal version of func1 to use within this component class
this.func1 = func1.bind(this);
}
render(){
const calc = this.func1(10,20)
return /*<div>{calc}</div>*/
}
}
console.log(new DoSomething().func1(10, 10))// expect 10*10/3 = 33.33..
你可以像这样重复使用它:
import Function1 from './Function
class DoSomething extends Component{
render(){
<div>
<Function1 var1={1} var2={2}</div>
}
}
您的Function1是Function.js的单独文件
export default (props) => ( console.log(props); // do anything you want )
PS你也可以在这里命名导出,但这取决于。