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

React hooks: How to merge a event.target.name and event.target.value to an object using useState

我有一个 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>
  );
}

但我得到的不是对象上的 属性:

如何获得:

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

试试这个:

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

希望对您有所帮助:)

你想覆盖状态还是只是一些更新?

我还没有测试过,但看来你需要做这样的事情:

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

希望对您有所帮助!