首页 > 解决方案 > 编译 React 时出错无法设置未定义的属性“道具”

问题描述

我的代码有问题

TypeError: Cannot set property 'props' of undefined

我认为我做的一切都是正确的。我什至引用 react cannot set property of props of undefined and React-router: TypeError: Cannot set property 'props' of undefined 了无法找出错误。作为一个新的编码员,我将不胜感激任何能够在未来找出这个错误的提示

我正在尝试创建联系我们页面。我在尝试编译页面时收到编译错误。请帮忙。

import React,{ Component } from 'react';
import axios from 'axios';
// import { render } from '@testing-library/react';

export class Contact extends Component(){
     state = {
        name: '',
        message: '',
        email: '',
        sent: false,
        buttonText: 'Send Message'
    }
    render(){
    return (
        <form className="contact-form" onSubmit={ (e) => this.formSubmit(e)}>
  <label class="message" htmlFor="message-input">Your Message</label>
  <textarea onChange={e => this.setState({ message: e.target.value})} name="message" class="message-input" type="text" placeholder="Please write your message here" value={this.state.message} required/>

  <label class="message-name" htmlFor="message-name">Your Name</label>
  <input onChange={e => this.setState({ name: e.target.value})} name="name" class="message-name" type="text" placeholder="Your Name" value={this.state.name}/>

  <label class="message-email" htmlFor="message-email">Your Email</label>
  <input onChange={(e) => this.setState({ email: e.target.value})} name="email" class="message-email" type="email" placeholder="your@email.com" required value={this.state.email} />

  <div className="button--container">
      <button type="submit" className="button button-primary">{ this.state.buttonText }</button>
  </div>
</form>
    )
 }
 formSubmit = (e) => {
    e.preventDefault()
  
    this.setState({
        buttonText: '...sending'
    })
  
    let data = {
        name: this.state.name,
        email: this.state.email,
        message: this.state.message
    }
    
    axios.post('API_URI', data)
    .then( res => {
        this.setState({ sent: true }, this.resetForm())
    })
    .catch( () => {
      console.log('Message not sent')
    })
  }
  resetForm = () => {
    this.setState({
        name: '',
        message: '',
        email: '',
        buttonText: 'Message Sent'
    })
}
}

图片

标签: reactjs

解决方案


您以错误的方式扩展了组件。Component是 aclass并且不能扩展为 afunction call

这就是你扩展的方式

export class Contact extends Component(){...

它应该是

export class Contact extends Component {...


推荐阅读