TypeError:无法读取未定义的属性“ handleSubmit”

时间:2018-12-04 14:31:56

标签: reactjs material-ui

我正在使用材料ui设计UI框架

     function handleSubmit(){
                alert("success");
            }
            function SignIn(props) {
            const { classes } = props;
            handleSubmit();
            return (<form className={classes.form} onSubmit={this.handleSubmit()}>
                  <FormControl margin="normal" required fullWidth>
                  <InputLabel htmlFor="email">Email Address</InputLabel>
                  <Input id="email" name="email" autoComplete="email" autoFocus />
                  </FormControl>
</form>

错误堆栈

                    60 | <Typography component="h1" variant="h5">
                61 |   Sign in
                62 | </Typography>
                > 63 | <form className={classes.form} onSubmit={this.handleSubmit()}>
                    | ^  64 |   <FormControl margin="normal" required fullWidth>
                65 |     <InputLabel htmlFor="email">Email Address</InputLabel>
                66 |     <Input id="email" name="email" autoComplete="email" autoFocus />

有人让我知道哪里出了问题吗?                         `

2 个答案:

答案 0 :(得分:0)

您可以尝试--

onSubmit={()=> this.handleSubmit()}

我认为问题肯定是Lexical scoping in Javascript

答案 1 :(得分:0)

您在这里遇到一些问题:

  1. 您正在功能组件内调用handleSubmit()。那只能由您的表格调用
  2. 不应在onSubmit中调用处理函数。使用onSubmit={this.handleSubmit}代替onSubmit={this.handleSubmit()}
  3. 使用功能组件(而不是类)时,没有this对象,因此也没有this.props
  4. 如果使用处理函数,则应使用一个类。请参见下面的示例。

    class SignIn extends Component {
      constructor(props) {
        super(props);
    
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleSubmit = function(){
         alert("success");
      }
    
      render() {
        const { classes } = this.props;
    
        return (<form className={classes.form} onSubmit={this.handleSubmit}>
          <FormControl margin="normal" required fullWidth>
            <InputLabel htmlFor="email">Email Address</InputLabel>
            <Input id="email" name="email" autoComplete="email" autoFocus />
          </FormControl>
         </form>);
      }
    }
    
相关问题