我的代码中有两个选择下拉列表。一个是教师列表,另一个下拉列表是课程列表。它必须采取多种选择。我在这里静态地为单个教师设置课程。如果我单击任何一位教师,则应该显示与教师相关的课程。以同样的方式,我有一个普通课程列表。我也应该显示课程列表。如果单击老师时将存在任何课程,则我不希望在课程列表中显示该课程。
import React from 'react'
import ReactDOM from 'react-dom'
import { Select, Button } from 'antd';
const Option =Select.Option
const teacherInfo=['Vikram','Ramesh']
const courseInfo = ['CULT1A','CULT1B','CULT1C','CULT1D','CULT1E','CULT1F','HINDI1A','HINDI1B',
'HINDI1C','HINDI1D','HINDI1E','HINDI1F'];
const teacherCourseData={
Vikram:['CULT1A','CULT1B','CULT1C','HINDI1A','HINDI1B'],
Ramesh:['CULT1D','CULT1E','HINDI1E','HINDI1F']
}
class TeacherCourse extends React.Component{
state={
selectTeacherValue:teacherCourseData[teacherInfo[0]],
selectCourseValue:teacherCourseData[teacherInfo[0]][0],
}
handleTeacherChange=
(value)=>{
this.selectTeacherValue=teacherCourseData[value]
this.selectCourseValue=teacherCourseData[value][0]
console.log(this.selectTeacherValue)
}
handleCourseChange=
(value)=>{
this.selectCourseValue=value
console.log(this.selectCourseValue)
}
handleClick=()=>{
console.log(this.selectCourseValue)
console.log(this.selectTeacherValue)
if(this.selectCourseValue === undefined || this.selectTeacherValue === undefined)
{
console.log("please select")
return;
}
else{
console.log("Sucessfully updated")
}
}
render()
{
const {selectCourseValue,selectTeacherValue}=this.state
{/*const filteredCourseOptions = courseInfo.filter(o => !selectCourseValue.includes(o));*/}
return(
<div align="center">
<h2>Shishu Bharathi</h2>
<label>Teacher List :</label>
<Select defaultValue="Select" style={{ width: 120 }}
onChange={this.handleTeacherChange}>
{teacherInfo.map(teacher=>(
<Option key={teacher}>{teacher}</Option>
))}
</Select>
<label>Course List :</label>
<Select
mode="multiple"
placeholder="Please select"
onChange={this.handleCourseChange}
style={{ width: 350 }}
>
{
selectTeacherValue.map(course=>(
<Option key={course} >{course}</Option>
)
)
}
</Select>
<br></br>
<br></br>
<Button onClick={this.handleClick}>Update</Button>
</div>
)
}
}
export default TeacherCourse
答案 0 :(得分:1)
您已经很接近了,但是好像您在反应中缺少了setState
函数。例如
handleCourseChange = (value) => {
this.selectCourseValue = value
console.log(this.selectCourseValue)
}
将成为
handleCourseChange = (value) => {
this.setState({ selectCourseValue: value })
console.log(this.state.selectCourseValue)
}
有关setState
的更多信息,请查看官方的React文档:https://reactjs.org/docs/react-component.html#setstate