Javascript 如何在ReactJS文件中正确导入函数
在react中导入函数时遇到问题。我使用Javascript 如何在ReactJS文件中正确导入函数,javascript,reactjs,function,Javascript,Reactjs,Function,在react中导入函数时遇到问题。我使用export default导出函数。然而,在导入它之后,我尝试在渲染函数中绑定它,但我得到一个错误,错误是TypeError:cannotreadproperty'bind'of undefined。这是否意味着函数没有正确导入?如何在React中正确导入它 import onSignUp from '../../functions/onsignup' class ModalExample extends React.Component {
export default
导出函数。然而,在导入它之后,我尝试在渲染函数中绑定它,但我得到一个错误,错误是TypeError:cannotreadproperty'bind'of undefined
。这是否意味着函数没有正确导入?如何在React中正确导入它
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
this.onSignUp=this.onSignUp.bind(this);
}
render(){
return(...)
}
这是否意味着函数没有正确导入
可能是的
如何在React中正确导入它
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
this.onSignUp=this.onSignUp.bind(this);
}
render(){
return(...)
}
从'/directorypath'导入导出函数代码>//如果使用默认值导出
从'./directorypath'导入{exportedFunction}代码>//如果导出时未使用默认值
组件的代码片段可以更好地描述问题。看起来您在其中有一个额外的括号,而且导入的函数将只是onSignUp
而不是this.onSignUp
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
this.onSignUp = onSignUp.bind(this);
}
render(){
return(...)
}
}
您应该在ctor
中绑定函数,或者在类中将其分配给onSignup
,如下所示:
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
onSignUp = onSignUp.bind(this);
render(){
return(...)
}
}
(我认为)也许你可以像这样在构造函数中声明你导入的onSignUp
而不是这个。onSignUp
不存在:
constructor(props) {
super(props);
this.onSignUp = onSignUp.bind(this);
}
你能给我们看一下onSignUp文件中的函数吗?根据它是什么函数,您可能不需要绑定它,但是
this.onSignp=this.onSignUp.bind(this)
在构造函数中执行此操作将假定您正在初始化一个新函数,而不是正在导入的函数,请改用此函数
this.onSignp = onSignUp.bind(this);
并确保从声明的位置正确地定义它,如果从React类外部导入函数,则无需在React类内部绑定它。您只需导入并使用它。见下文
函数/onsignup.js
在此处定义并导出函数
const onSignUp = () =>{
// function code here
}
export default signup;
ModalExample.js
在此处导入函数并使用
import React, {Componenet} from 'react';
import onSignUp from '../../functions/onsignup'
class ModalExample extends React.Component {
constructor(props) {
super(props);
}
render(){
return(
<button onClick={()=>onSignUp()} />
)
}
}
import React,{Componenet}来自'React';
从“../../functions/onSignUp”导入onSignUp
类ModalExample扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
onSignUp()}/>
)
}
}
请同时添加相关代码。您错误地使用了bind
。添加代码以获得答案。尝试在控制台中打印导入的函数,如果未定义,则函数未正确导入或导出this.onSignUp
此函数的定义在哪里?它是导入的函数,而不是类函数,以this.onSignUp.bind
的身份访问它。您可以像这样直接使用它。onSignUp=onSignUp.bind(this)
。