ReactJS/Material-Table:如果有人选择了某个 "lookup"/下拉选项,我如何自动填充行?
ReactJS/Material-Table: How can I autofill a row if someone selects a certain "lookup"/dropdown option?
问题: 我如何使用 Material-Tables "lookup" 函数尝试根据所选内容预填充行。
我有一个包含所有重要值的数组,如果我要使用查找值来选择某人,我希望它然后 "prefill" 使用基于该数组的数据的行。
相关代码:
var arrayLookupValues = [
{ name: "John Adams", birthYear: "1826", birthCity: "Massachusetts" },
{ name: "Thomas Jefferson", birthYear: "1743", birthCity: "Virginia" },
{ name: "George Washington", birthYear: "", birthCity: "" }
];
columns: [
{
title: "Name",
field: "name",
lookup: {
1: "John Adams",
2: "Thomas Jefferson",
3: "George Washington"
}
},
{ title: "Birth Year", field: "birthYear" },
{
title: "Birth Place",
field: "birthCity"
}
],
代码沙箱:
https://codesandbox.io/s/material-demo-0q5zo?fontsize=14&hidenavigation=1&theme=dark
我想尝试做的事的一个例子:
然后当约翰亚当斯被选中时,出生年份和出生地点被填充(如下例)。
如果选择乔治华盛顿,由于 "arrayLookupValues" 不包含他的出生年份或出生城市,我希望它只是将字段留空。
我已经尝试在 onRowAdd 中使用 onClick(本质上是将 newData 设置为我想要的特定数组值)。问题是一旦您单击 "tick",数据只会在单击它之后而不是之前被预填充。
我希望有人能够单击 "plus" 按钮,然后从查找中选择一个选项,然后在单击勾号之前预填充该行以保存到 "data" 数组中。
您可以简单地将字段的 editComponent 覆盖为 return 所选值的匹配数据:
editComponent: ({ onChange, onRowDataChange, ...props }) => {
const onCustomChange = value => {
const lookup = props.columnDef.lookup;
const matchingValue = jsonContainingValues.find(
val => val.name === lookup[value]
);
const newValue = { ...matchingValue };
newValue.name = value;
onRowDataChange(newValue);
};
return <MTableEditField onChange={onCustomChange} {...props} />;
},
通过使用 onRowDataChange
更新数据,您可以覆盖整个对象而不是当前字段。
这是你的 sandbox.
的分支
问题: 我如何使用 Material-Tables "lookup" 函数尝试根据所选内容预填充行。
我有一个包含所有重要值的数组,如果我要使用查找值来选择某人,我希望它然后 "prefill" 使用基于该数组的数据的行。
相关代码:
var arrayLookupValues = [
{ name: "John Adams", birthYear: "1826", birthCity: "Massachusetts" },
{ name: "Thomas Jefferson", birthYear: "1743", birthCity: "Virginia" },
{ name: "George Washington", birthYear: "", birthCity: "" }
];
columns: [
{
title: "Name",
field: "name",
lookup: {
1: "John Adams",
2: "Thomas Jefferson",
3: "George Washington"
}
},
{ title: "Birth Year", field: "birthYear" },
{
title: "Birth Place",
field: "birthCity"
}
],
代码沙箱:
https://codesandbox.io/s/material-demo-0q5zo?fontsize=14&hidenavigation=1&theme=dark
我想尝试做的事的一个例子:
然后当约翰亚当斯被选中时,出生年份和出生地点被填充(如下例)。
如果选择乔治华盛顿,由于 "arrayLookupValues" 不包含他的出生年份或出生城市,我希望它只是将字段留空。
我已经尝试在 onRowAdd 中使用 onClick(本质上是将 newData 设置为我想要的特定数组值)。问题是一旦您单击 "tick",数据只会在单击它之后而不是之前被预填充。
我希望有人能够单击 "plus" 按钮,然后从查找中选择一个选项,然后在单击勾号之前预填充该行以保存到 "data" 数组中。
您可以简单地将字段的 editComponent 覆盖为 return 所选值的匹配数据:
editComponent: ({ onChange, onRowDataChange, ...props }) => {
const onCustomChange = value => {
const lookup = props.columnDef.lookup;
const matchingValue = jsonContainingValues.find(
val => val.name === lookup[value]
);
const newValue = { ...matchingValue };
newValue.name = value;
onRowDataChange(newValue);
};
return <MTableEditField onChange={onCustomChange} {...props} />;
},
通过使用 onRowDataChange
更新数据,您可以覆盖整个对象而不是当前字段。
这是你的 sandbox.