如何从对象类型为 State 的字段中捕获 onChange 事件

How to capture onChange event from a field with object type State

我无法从本身包含多个对象字段的对象捕获 onChange 事件。

这是我的 useState 钩子。

    const [train, setTrain] = useState({
    trainNumber: "",
    trainName: "",
    fromStation: "",
    toStation: "",
    departureDateTime: "",
    arrivalDateTime: "",
//unable to capture travelDetails property changes.
    travelDetails: {   
      coachesClass: [
        {
          availableTickets: "",
          travelClass: "",
          fare: "",
        },
      ],
    },
  });

假设我想检查 travelDetails.coachesClass[0].availableTickets 的 onChange 事件,那么该怎么做?

        <div className="row">
          <label htmlFor="availableTickets">First AC</label>
          <div className="col-4">
            <input
              type="number"
              name="availableTickets"
              className="form-control"
              placeholder="Available Tickets"
              required
              value={train.travelDetails.coachesClass[0].availableTickets}
              onChange={(e) => handleChange(e)}
            />
          </div>

这里是 onChangeHandler

const handleChange = (e) => {
const { name, value } = e.target;
setTrain((prevState) => {
  return {
    ...prevState,
    [name]: value,
  };
});

};

它对其他字段工作正常,但在 travelDetails 内部它没有捕获更改。

目前,您的 setState 在状态对象本身上添加了一个新的 属性。由于您似乎希望该信息更新您的嵌套状态,请参阅下面更新的代码段:

const handleChange = (e) => {
const { name, value } = e.target;
  setTrain((prevState) => {
      return {
        ...prevState,
        travelDetails: {
          ...prevState.travelDetails,
          coachesClass: [
            {
              ...prevState.travelDetails.coachesClass[0],
              [name]: value
            }
          ]
        }
      };
    });

您更新状态的方式需要调整,因为您正尝试更新嵌套在对象中的数组中的 属性。尝试这样的事情:

  const handleChange = (e) => {
    setTrain((prevState) => {
      const newCoachesClass = [...prevState.travelDetails.coachesClass];
      newCoachesClass[0] = {
        ...prevState.travelDetails.coachesClass[0],
        availableTickets: e.target.value
      };
      return {
        ...prevState,
        travelDetails: {
          ...prevState.travelDetails,
          coachesClass: newCoachesClass
        }
      };
    });
  };

此外,由于您的 inputnumber 类型,您可能希望将 availableTickets 初始化为数字而不是字符串:

const [train, setTrain] = useState({
    trainNumber: "",
    trainName: "",
    fromStation: "",
    toStation: "",
    departureDateTime: "",
    arrivalDateTime: "",
    travelDetails: {   
      coachesClass: [
        {
          availableTickets: 0,
    ...

查看此代码笔以获取示例: