简体   繁体   English

Reactjs,我该如何添加选择选项属性值来声明

[英]Reactjs, How can I add select option attributes values to state

I have a small app that has a small form. 我有一个小型的小型应用程序。 the form has these fields: 表单具有以下字段:

Course- created mapping over a props object element called courseName 课程创建的映射到名为courseName的道具对象元素上

Select- a select field with fixed values. 选择-具有固定值的选择字段。

Course grade- number type field. 课程成绩-数字类型字段。

In the app state I have two arrays: 在应用程序状态下,我有两个数组:

  1. courses: is the data that creates the form select options 路线:是创建表单选择选项的数据

  2. newCourse: contains the data that is submitted in the form. newCourse:包含以表单提交的数据。

    state = { courses: [ { id: 1, courseName: 'English', courseType: false, courseHours: 10, courseGrade: '', coursePassGrade: 55 },{ id: 2, courseName: 'Math', courseType: true, courseHours: 8, courseGrade: '', coursePassGrade: 55 },{ id: 3, courseName: 'Biology', courseType: false, courseHours: 30, courseGrade: 50, coursePassGrade: 70 } ], newCourses:[] }

I use 我用

onChange(e) {
    this.setState({
         [e.target.name]: e.target.value });
}

in order to update the state with the form field value. 为了用表单字段值更新状态。

My problem is that I want to add to the newCourse state values from the course props. 我的问题是我想从course道具中添加到newCourse状态值。 I have added this data to the option attributes. 我已将此数据添加到选项属性。 my question is how can I retrieve the option attributes in order to add these values ( courseHours and coursePassGrade see courses const bellow) from course props to the newCourse state This is the form component 我的问题是如何检索选项属性以将这些值( courseHourscoursePassGrade请参阅courses const bellow)从course道具添加到newCourse状态,这是表单组件

import React, { Component } from 'react';
import { Form, Button, Col, Row } from 'react-bootstrap';

class AddCourse extends Component {

    state = {
        courseName: '',
        courseType: '',
        courseGrade: '',
        courseHours: '',
        coursePassGrade: ''
    }

    onChange(e) {
        console.log('e.target', e.target.coursehours);


        this.setState({
             [e.target.name]: e.target.value });
    }

    onSubmit = (e) => {
        e.preventDefault();
        this.props.addCourse(this.state);
        this.setState({
            courseName: '',
            courseType: '',
            courseGrade: ''
        })
    }
    render() {
        const courses = this.props.courses.map(course =>
            <option 
                key={course.id} 
                value={course.courseName} 
                coursehours={course.courseHours} 
                coursepassgrade={course.coursePassGrade}  
            >
                {course.courseName}
            </option>
        )

        return (
            <div>
                <Form onSubmit={this.onSubmit}>
                    <Row>
                        <Col>
                            <Form.Group controlId="exampleForm.ControlSelect1">

                                <Form.Control
                                    as="select"
                                    name="courseName"
                                    defaultValue={this.state.courseName}
                                    onChange={this.onChange.bind(this)}
                                >
                                <option value="">Course...</option>
                                    {courses}

                                </Form.Control>
                            </Form.Group>
                        </Col>
                        <Col>
                            <Form.Group controlId="formGridState">

                                <Form.Control as="select"
                                    name="courseType"
                                    defaultValue={this.state.courseType}
                                    onChange={this.onChange.bind(this)}
                                >
                                    <option value="">Select...</option>
                                    <option value="true">a</option>
                                    <option value="false">m</option>
                                </Form.Control>
                            </Form.Group>
                        </Col>
                        <Col>
                            <Form.Group controlId="formBasicGrade">
                                <Form.Control
                                    type="number"
                                    placeholder="Course grade"
                                    name="courseGrade"
                                    defaultValue={this.state.courseGrade}
                                    onChange={this.onChange.bind(this)}
                                />
                            </Form.Group>

                            <Form.Group controlId="courseHours">
                                <Form.Control
                                    type="hidden"
                                    name="courseHours"
                                    defaultValue={this.props.courseHours}

                                />
                            </Form.Group>
                        </Col>
                        <Col>
                            <Form.Group controlId="submit">
                                <Button variant="primary" type="submit">
                                    Submit
                        </Button>
                            </Form.Group>
                        </Col>
                    </Row>
                </Form>
            </div>
        )
    }
}

export default AddCourse

Try changing your courses const to this: 尝试将您的课程const更改为此:

        const courses = this.props.courses.map((course, n) =>
            <option 
                key={course.id} 
                value={n} 
            >
                {course.courseName}
            </option>
        )

And your event handler to this: 和您的事件处理程序:

    onChange(e) {
        const { courses } = this.props
        const n = e.target.value
        const { courseName, courseHours, coursePassGrade } = courses[n]
        this.setState({ courseName, courseHours, coursePassGrade, })
    }

It is correct for you, in App , to keep the state with your list of courses and then with any courses added through the submission of the form. App ,保持课程列表的state ,然后通过提交表单添加的所有课程保持state是正确的。

The addCourse handler which you pass from App to AddCourse should look something like this: App传递到AddCourseaddCourse处理程序应如下所示:

// App.js

addCourse = ({ courseName, courseType, courseGrade }) => {

  const { coursePassGrade, courseHours } = this.getCourseByName(courseName)
  const newCourse = {
      courseName,
      courseType,
      courseGrade,
      coursePassGrade,
      courseHours
    }
    const updatedNewCourses = [...this.state.newCourses]
    updatedNewCourses.push(newCourse)
    this.setState({ newCourses: updatedNewCourses })

}

In AddCourse , when you call the addCourse handler, you pass up (to App ) all of the data that you have from the form ( courseName , courseGrade , and courseType ). AddCourse ,当您调用addCourse处理程序时, addCourse所有数据( courseNamecourseGradecourseType )传递(到App )。 You do not need to keep track of the corresponding coursePassGrade or courseHours in your AddCourse component. 您无需在AddCourse组件中跟踪相应的coursePassGradecourseHours It can be the job of App to find those remaining attributes by searching in his this.state.courses based on the courseName that he was given. 通过根据给定的courseName在他的this.state.courses进行搜索,可以找到这些剩余的属性,这是App的工作。

As you can see from above, this is the job of getCourseByName : 从上面可以看到,这是getCourseByName的工作:

// App.js

getCourseByName = (courseName) => {

  const index = this.state.courses.findIndex((course) => {
    return (course.courseName === courseName)
  })
  return this.state.courses[index]

}

This method looks up (in this.state.courses ) the course attributes based on the name, and it returns the entire course object. 此方法根据名称查找(在this.state.courses )课程属性,并返回整个课程对象。 When you call this, in addCourse , you only care about the coursePassGrade and courseHours , which is what you use to continue building the newCourse object which will be pushed to this.state.newCourses 当您在addCourse调用此addCourse ,您只关心coursePassGradecourseHours ,这就是您用来继续构建将被推送到this.state.newCoursesnewCourse对象的this.state.newCourses

I have used your code to put together a CodeSandbox which shows these techniques in action. 我已使用您的代码将CodeSandbox放在一起,以展示实际中的这些技术。 I hope it is helpful to you in giving you some direction. 希望它对您有所帮助。

编辑课程添加-状态的选项和属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM