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