How to change parent array element in state from child component using reactjs?

问题描述 投票:0回答:1

我有一些值的数组和一个应该包含这些值的表。每个单元格不仅包含一个值,还包含一个允许编辑值的文本输入。此文本输入是我的自定义元素。所以,我将值从父状态数组传递到我的输入,但我该如何更改它?

这是我的状态:

const [state, setState] = useState<State>({
    hourlySpeed: hourlySpeed,
    loading: loading,
});

这就是我将价值传递给孩子的方式:

<th><ControlledInput
    binding={state.hourlySpeed[i].hour1}
    className={"hourlySpeedInput"}/>
</th>

这是我的子组件:

type Props = {
    binding: any
    className: string
}

export const ControlledInput: React.FC<Props> = ({
    binding, className
}) => {
    return <input type="text"
        className={className}
        value={binding}>
    </input>
}
reactjs typescript react-hooks parent-child
1个回答
0
投票

setState
作为prop传递给输入,然后在
onChange
中使用:

export const ControlledInput: React.FC<Props> = ({binding, className, setState}) => {
  return (
    <input type="text"
      className={className}
      value={binding}>
      onChange={(e) => {
        const newVal = e.target.value;
        setState(prev => {
          // return ...
        })
      }}
    </input>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.