javascript - React Js 使用 onChange 将数组内的值更新为子组件

标签 javascript arrays reactjs components

我有一个包含 opening_hours 的列表,我将其映射到渲染函数中。我将它们映射到子组件。我想在子组件状态更改时更改父状态中每个对象的值。唯一的问题是我的值在子组件和父状态中都没有改变。我已将 onChange 方法传递给每个子组件,但问题出在我的父状态下的 onChange 函数。

我尝试将 onChange 传递给我的子组件并使用 [e.target.name] : e.target.value 更新状态。但这没有用。所以我尝试复制 arrayList 并根据映射的 arrayList 的索引更新状态。那也行不通。

    handleOnChange =  (index) => {
        let newData = [...this.state.opening_hours];
        this.setState(
            newData.map((barbershop, j) => {
                if (j === index) {
                    return barbershop;
                    console.log(barbershop)
                }
            return {
                newData,
            };
        }));
        console.log(newData)
    };

    render() {
        return (
            <>
                <div className="container mb-2">
                    <h4>Opening hours </h4>
                    <Form>
                        {this.state.opening_hours.map((barbershop, index) => (
                            <Day
                                key={barbershop.id}
                                day={barbershop.day}
                                open_time={barbershop.open_time}
                                close_time={barbershop.close_time}
                                index = {index}
                                onChange={() => this.handleOnChange(index)}/>
                        ))}
                    </Form>


                    <Button onClick={this.handleSubmit} variant="primary" type="submit">
                        Update opening hours
                    </Button>
                </div>
            </>
        );
    }
}

我的子组件看起来像这样

class Day extends Component {

    constructor(props) {
        super(props);
        this.state = {
            day: this.props.day,
            open_time: this.props.open_time,
            close_time: this.props.close_time,
        };
        console.log(this.state)
    }

    handleChange = () => {
        this.props.onChange(this.props.index)
    }

    render() {
        return (
                <Form.Group as={Row}>
                <Form.Label column sm="3">
                    {ENUM[this.state.day]}
                </Form.Label>
                <Col sm="3">
                    <Form.Control
                        name="open_time"
                        value={this.state.open_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
                <Col sm="3">
                    <Form.Control
                        name="close_time"
                        value={this.state.close_time}
                        onChange={this.handleChange}
                        type="time"
                        min="08:00"
                        max="24:00"/>
                </Col>
            </Form.Group>
        );
    }
}

EDIT:

enter image description here

最佳答案

所以我做了一些调查,我相信问题是你没有将数据返回给消费者。

这是我的想法,解决方案是:

import React, { Component, useState, useEffect } from "react";

class UI extends Component {
  handleOnChange = ({ index, ...newHours }) => {
    // update array item
    const opening_hours = this.state.opening_hours.map((item, i) => {
      const newData = i === index ? newHours : {};

      return {
        ...item,
        ...newData
      };
    });

    // update item in opening_hours => state
    this.setState({ opening_hours });
  };

  render() {
    return (
      <div className="container mb-2">
        <h4>Opening hours</h4>

        <Form>
          {this.state.opening_hours.map(({ id, ...barbershop }, index) => (
            <Day
              key={id}
              {...barbershop}
              {...{ index }}
              onChange={this.handleOnChange}
            />
          ))}
        </Form>

        <Button onClick={this.handleSubmit} variant="primary" type="submit">
          Update opening hours
        </Button>
      </div>
    );
  }
}

const Day = ({ day, onChange, index, ...props }) => {
  const [open_time, setOpenTime] = useState(props.open_time);
  const [close_time, setCloseTime] = useState(props.close_time);

  useEffect(() => {
    onChange({ index, open_time, close_time });
  }, [open_time, close_time, onChange, index]);

  const sharedProps = {
    type: "time",
    min: "08:00",
    max: "24:00"
  };

  return (
    <Form.Group as={Row}>
      <Form.Label column sm="3">
        {ENUM[day]}
      </Form.Label>

      <Col sm="3">
        <Form.Control
          {...sharedProps}
          name="open_time"
          value={open_time}
          onChange={({ target }) => setOpenTime(target.value)}
        />
      </Col>

      <Col sm="3">
        <Form.Control
          {...sharedProps}
          name="close_time"
          value={close_time}
          onChange={({ target }) => setCloseTime(target.value)}
        />
      </Col>
    </Form.Group>
  );
};

关于javascript - React Js 使用 onChange 将数组内的值更新为子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407122/

相关文章:

C - 计算数组中相同数字的出现次数

java - 将 2D ArrayList 代码更改为 2D 数组代码

node.js - 如何从 Express 将 400 错误的 json 数据返回到 React?

Javascript 在选中复选框时隐藏/取消隐藏文件上传

javascript - 检查元素是否具有纯 JS 的背景图像?

javascript - Twitter Bootstrap + Google Maps 仍然无法使用错误修复

javascript - 如何在水平滚动上添加平滑滚动效果?

c - 如何从字符串数组中仅获取所需的元素

javascript - Laravel + React : this. state.tasks.map 不是一个函数

javascript - 输入上的 onChange 不会使用 setState 更新状态