我有一个要通过钩子操作的数据结构:https://stackblitz.com/edit/react-ts-sg6ahi?file=index.tsx
export interface Criteria{
criterions?: Criterion[]
}
export interface Criterion{
key?: string;
value?: string;
}
这是我要实现的目标:
1.单击添加新的空标准时。
2.当我更改输入文本并导致整个上下文更改时。
目前,什么都没有...
我已经声明了全局上下文并通过了它。
export const initial = {criterions:[{key:'Key1', value: 'Value1'},{key:'Key2', value: 'Value2'}]}
export const CriteriaContext = React.createContext<Criteria>(initial);
const App = () => {
let context = useContext(CriteriaContext);
const [criteria, setCriteria] = useState<Criteria>(context);
const addCriterion = () =>{
criteria.criterions.push({});
setCriteria(criteria);
}
return <CriteriaContext.Provider value={criteria}>
<button onClick={addCriterion}>Add new empty criterion {context.criterions.length}</button> <br /> <br />
<CriteriaComponent criteria={criteria} />
</CriteriaContext.Provider>
}
const CriteriaComponent = (props) => {
let context = useContext(CriteriaContext);
return (
<div>
<b>Criterions list:</b><br />
{context.criterions && context.criterions.map((x,y) =>
<div>{y}) <CriterionComponent key={y} criterion={x} /></div>
)}
<div>
<hr />
<h2>The criteria serialized (with value changes):</h2>
<code>{JSON.stringify(context)}</code>
</div>
</div>
)
}
const CriterionComponent = (props: {criterion:Criterion}) => {
return (
<span>
key = <input type="text" name="key" value={props.criterion.key} />
value = <input type="text" name="value" value={props.criterion.value} />
</span>
)
}
https://stackblitz.com/edit/react-ts-sg6ahi?file=index.tsx
谢谢