开发者问题收集

Material-ui 按钮 onClick() 导致“Uncaught TypeError: Cannot read property 'name' of undefined”错误

2018-06-22
3437

我有一个 Material UI 按钮,它有一个 OnClick 函数。但出于某种原因,当我点击按钮时,它不起作用,并给出了上面显示的错误。

我可以知道我在这里做错了什么吗? 我按照这里的建议使用了构造函数: 建议的解决方案 但它仍然不起作用

Props

type Props = {
  showSmallHero: () => void,
  fetchTalentIfNeeded: () => void,
  submitJobApplicationIfNeeded: () => void,
  talent: Object,
};

我的代码

  componentDidMount() {
    this.props.showSmallHero();
    this.props.fetchTalentIfNeeded();
  }

  handleChange = (event, d) => {
    const { target } = event;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    if (d.name === 'gender') {
      this.setState({
        [d.name]: d.value,
      });
    } else if (d.name === 'resume') {
      // This is a file
    } else {
      const { name } = target;
      this.setState({
        [name]: value,
      });
    }
  };

  handleSubmit = () => {
    const fileInput = document.getElementById('resume');
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('full-name', this.state.fullName);
    formData.append('gender', this.state.gender);
    formData.append('nric', this.state.nationalId);
    formData.append('email', this.state.email);
    formData.append('phone-number', this.state.phoneNumber);
    formData.append('position-applied', this.state.jobName);
    formData.append('job-id', this.state.jobId);
    formData.append('experience', this.state.experience);
    formData.append('academic-result', this.state.academicResult);
    formData.append('resume', file);
    this.props.submitJobApplicationIfNeeded(formData);
  };

  handleClick = (e, d) => {
    this.setState({ jobName: d.name, jobId: d.id, showModal: true });
  };

  hideModal = () => {
    this.setState({ showModal: false });
  };


render() {

<Button
     variant="contained"
     size="medium"
     color="secondary"
     id={t.acf.job_id}
     name={t.acf.job_name}
     onClick={this.handleClick}
     >
     Apply
     </Button>
}

任何帮助都非常感谢。

1个回答

您没有在 onClick 方法上使用 handleClick 函数传递任何参数,并且您尝试从未定义的参数中访问某些键,因此您会收到错误 无法读取未定义的属性名称 。请尝试将参数传递给该 handleClick 函数:

<Button
 variant="contained"
 size="medium"
 color="secondary"
 id={t.acf.job_id}
 name={t.acf.job_name}
 onClick={()=>this.handleClick(param1,param2)}
 >
 Apply
 </Button>
aravind_reddy
2018-06-22