[英]imported functions don't work under render()
I am attempting to move a bunch of reusable functions into a convenient place, but I'm having issues with using them in other files.我试图将一堆可重用的函数移到一个方便的地方,但是我在其他文件中使用它们时遇到了问题。 I am using a static React.js frontend without Node.
我正在使用没有 Node.js 的静态 React.js 前端。
miscFunctions.js miscFunctions.js
export const capitalize = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = {
capitalize,
other functions...
}
Test.js测试.js
import React, { Component } from 'react';
import capitalize from './miscFunctions';
class Test extends Component {
constructor(props) {
super(props);
this.capitalize = capitalize.bind(this);
}
render() {
return (
<div>
{this.capitalize("foo")}
</div>
);
}
}
export default Test;
capitalize() works just fine so long as it's used in a class function, but once I try to use it within render(), it doesn't exist. capitalize() 只要在类函数中使用它就可以正常工作,但是一旦我尝试在 render() 中使用它,它就不存在了。 I get the message "TypeError: Cannot read property 'bind' of undefined"
我收到消息“类型错误:无法读取未定义的属性‘绑定’”
You don't need to put the capitalize
function on the component at all.您根本不需要将
capitalize
函数放在组件上。 You can remove it from the constructor and just use it as is.您可以从构造函数中删除它,然后按原样使用它。
capitalize
is a named export, so you need to import it with that in mind. capitalize
是一个命名的导出,所以你需要记住这一点。
// miscFunctions.js
export const capitalize = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Test.js
import React, { Component } from 'react';
import { capitalize } from './miscFunctions';
class Test extends Component {
render() {
return (
<div>
{capitalize("foo")}
</div>
);
}
}
export default Test;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.