React挂钩:如何使用useState将event.target.name和event.target.value合并到对象

时间:2020-04-11 21:55:24

标签: reactjs react-hooks use-state

我有一个changeHandler,用于在父组件中添加状态:

  function handleChange(event) {
      var { name, value } = event.target;
      if (dayInfoInChild.hasOwnProperty(currentDate)) {
        setDayInfoInChild({ ...dayInfoInChild.currentDate, [name]: value });
      }
    }

这是所有代码:

import { Header, Table, TextArea } from 'semantic-ui-react';
import React, { useState, useEffect } from 'react';

export default function Day({ dayInfo, props }) {
  var [dayInfoInChild, setDayInfoInChild] = useState({});
  var [currentDate, setCurrentDate] = useState('');
  var [timeOfDay, setTimeOfDay] = useState('');

  function setExactHourHelper(index) {
    return index === 0 ? 12 : '' || index > 12 ? index - 12 : index;
  }

  function TimeOfDaySetter(index) {
    if (index === 0) {
      return <Header as="h1">AM</Header>;
    } else if (index === 12) {
      // setTimeOfDay('PM');
      return <Header as="h1">PM</Header>;
    }
  }

  useEffect(() => {
    if (dayInfo !== null) {
      var modifiedDayInfo = dayInfo
        .split(' ')
        .map((item) => {
          if (item.indexOf(',')) return item.replace(/,/g, '');
        })
        .join('-');

      setCurrentDate(modifiedDayInfo);

      if (localStorage.getItem(modifiedDayInfo)) {
        var stringVersionOfModifiedDayInfo = modifiedDayInfo;

        modifiedDayInfo = JSON.parse(localStorage.getItem(modifiedDayInfo));

        if (!dayInfoInChild.hasOwnProperty(stringVersionOfModifiedDayInfo)) {
          setDayInfoInChild({
            ...dayInfoInChild,
            [stringVersionOfModifiedDayInfo]: modifiedDayInfo,
          });
        }

        console.log('dayInfoInChild', dayInfoInChild);
        console.log(
          'stringVersionOfModifiedDayInfo',
          stringVersionOfModifiedDayInfo
        );
      } else {
        localStorage.setItem(modifiedDayInfo, JSON.stringify({}));
      }
    }
  }, [dayInfo, dayInfoInChild]);

  function TableLayout({}) {
    var [amountOfRows, setAmountOfRows] = useState(24);
    var [textValue, setTextValue] = useState('');

    function handleChange(event) {
      var { name, value } = event.target;
      if (dayInfoInChild.hasOwnProperty(currentDate)) {
        setDayInfoInChild({ [dayInfoInChild.currentDate]: { [name]: value } });
      }
    }

    const tableStyle = {
      borderLeft: 0,
      borderRight: 0,
    };

    const colorOveride = {
      color: '#C1BDBD',
    };

    return (
      <>
        {console.log('dayInfoInChild', dayInfoInChild)}
        <h1>{dayInfo}</h1>
        <Table celled structured>
          <Table.Body>
            {Array.from(Array(amountOfRows)).map((row, index) => {
              return (
                <React.Fragment key={index}>
                  <Table.Row>
                    <Table.Cell rowSpan="2" style={tableStyle}>
                      {TimeOfDaySetter(index)}
                    </Table.Cell>
                    <Table.Cell style={tableStyle}>
                      {
                        <strong>
                          {setExactHourHelper(index)}
                          :00
                        </strong>
                      }
                      <TextArea
                        rows={2}
                        name="textarea"
                        value={textValue}
                        onChange={handleChange}
                        placeholder="Tell us more"
                      />
                    </Table.Cell>
                  </Table.Row>
                  <Table.Row>
                    <Table.Cell style={(tableStyle, colorOveride)}>
                      {
                        <strong>
                          {setExactHourHelper(index)}
                          :30
                        </strong>
                      }
                      <TextArea rows={2} placeholder="Tell us more" />
                    </Table.Cell>
                  </Table.Row>
                </React.Fragment>
              );
            })}
          </Table.Body>
        </Table>
      </>
    );
  }

  {
    if (dayInfo === null) {
      return <p>Loading...</p>;
    }
  }

  return (
    <React.Fragment>
      <TableLayout dayInfo={dayInfo} />
    </React.Fragment>
  );
}

但是我得到了这个,而不是对象的属性:

![enter image description here

我如何获得:

dayInfoInChild: { April-16-2020: {textarea: "g"} }

2 个答案:

答案 0 :(得分:1)

尝试一下:

function handleChange(event) {
      var { name, value } = event.target;
      if (dayInfoInChild.hasOwnProperty(currentDate)) {
        setDayInfoInChild({ [dayInfoInChild.currentDate]: { [name]: value } });
      }
    }

希望它会有所帮助:)

答案 1 :(得分:1)

您要覆盖状态还是仅进行一些更新?

我尚未测试,但看来您需要执行以下操作:

function handleChange(event) {
      var { name, value } = event.target;
      if (dayInfoInChild.hasOwnProperty(currentDate)) {
        setDayInfoInChild({ 
           ...dayInfoInChild,
           [dayInfoInChild.currentDate]:{[name]: value} 
        }); 
      }
    }

希望对您有帮助!