但是,正如标题所述,尝试在我的类中声明一个组件时,会得到一个未定义的错误。我能不能不这么做,还是我做错了?就像我说的,我是新来的,所以任何一点信息都有帮助。总体目标是创建一个表单,但我只想让某些选项弹出,这取决于前面的选项是什么。如果代码太多,让我知道,我会把它缩减到什么是重要的,但我想我会提供整个事情,因为它没有那么长。
import React, {useState, useMemo} from 'react';
import ReactDOM from 'react-dom/client';
import countryList from 'react-select-country-list';
import './index.css';
//import App from './App';
class StartForm extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.options = countryList().getData();
}
handleChange(event) {
this.setState({[event.target.name]: event.target.value});
//alert('Your favorite flavor is: ' + this.state.value);
console.log(this.state.accType);
}
handleSubmit(event) {
//alert('Your favorite flavor is: ' + this.state.value);
//event.preventDefault();
}
//------------------- THIS COMPONENT
CustomOptions(props) {
return(
<label>
<input type="checkbox" id="acss_debit_payments" name="acss_debit_payments" value={this.value.acss_debit_payments} onChange={this.handleChange} />Paneer
</label>
);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Select Account Type:
<select name="accType" value={this.state.accType} onChange={this.handleChange}>
<option value="custom">Custom</option>
<option value="express">Express</option>
<option value="standard">Standard</option>
</select>
</label>
<br/>
<label>
Select Country Code(Optional):
<select name="country" options={this.options} value={this.state.country} onChange={this.handleChange}/>
</label>
<br/>
<label>
Email:
<input type="text" name="email" value={this.state.email} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
{this.state.accType == "custom" &&
<CustomOptions />
}
</form>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<StartForm/>
</React.StrictMode>
);发布于 2022-04-14 22:41:49
要调用CustomOptions,需要使用this引用当前实例
<this.CustomOptions />示例:https://codesandbox.io/s/happy-swartz-hsm6ng?file=%2Fsrc%2FApp.js
https://stackoverflow.com/questions/71878135
复制相似问题