gpt4 book ai didi

reactjs - 将 React 类函数存储在单独的文件中

转载 作者:行者123 更新时间:2023-12-03 13:41:06 25 4
gpt4 key购买 nike

有没有办法将 React 类的函数存储在单独的文件中,然后导入这些函数以供使用?想要这样做的原因纯粹是为了减少组件的大小并按类别对功能进行分组。

例如:

import functionIWantToImport from '../functions/functionIWantToImport';
import anotherFunction from '../functions/anotherFunction';

Class Test extends React.Component {
constructor(props){
super(props);

this.state = {};
}

//and then include the functions like below:
functionIWantToImport;
anotherFunction;
}

我知道我可以使用不属于组件类的辅助函数来做到这一点。但我想用我的组件函数来完成此操作,以节省空间并清理我的代码。

最佳答案

使用标准JS函数(不是箭头函数),并在构造函数中将函数绑定(bind)到实例:

function externalMethod() { // simulates imported function
return this.state.example;
}

class Test extends React.Component {
constructor(props){
super(props);

this.state = { example: 'example' };

this.externalMethod = externalMethod.bind(this);
}

render() {
return (
<div>{ this.externalMethod() }</div>
);
}
}

ReactDOM.render(
<Test />,
test
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="test"></div>

关于reactjs - 将 React 类函数存储在单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com