我正在嘗試基于兩個文本輸入字段中是否都存在任何字符來啟用/禁用表單按鈕,但是由于某種原因,狀態長度在我的條件下呈現了錯誤,盡管我登錄狀態時卻顯示了錯誤。錯誤:const isEnabled = this.state.subject.length > 0 && this.state.emails.length > 0; //Uncaught TypeError: Cannot read property 'length' of undefined完整代碼:import React from 'react';export default class EmailAnnotationForm extends React.Component { constructor(props) { super(props); this.state = { csrf: '', subject: '', emails: '', comment: '' } this.handleInputChange = this.handleInputChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); this.handleClearForm = this.handleClearForm.bind(this); this.input = React.createRef(); } componentDidMount() { console.log(this.state.subject.length) // renders correct value => 0 this.setState({subject: this.props.title }); } handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } handleClearForm() { this.setState({ csrf: '', subject: '', emails: '', comment: '' }) } handleFormSubmit(event) { var emailSubject; { this.state.subject ? emailSubject = this.state.subject : emailSubject = this.props.title }; // const body = { subject: emailSubject, emails: this.state.emails, comment: this.state.comment };
在空的輸入字段ReactJS上顯示錯誤
慕妹3146593
2021-04-17 18:15:13