是否将下拉值设置回占位符或按钮上单击事件后的第一个选项



在下面的代码中,我有一个Dropdown和一个Button。在下拉列表中选择一个选项并单击按钮后,该值将被发送到活动单元格中的Excel。将这些数据发送到Excel后,我可以将下拉菜单设置回占位符吗?或者我可以将Dropdown设置为第一个值(在本例中为空(吗?如何将Dropdown值设置回占位符或空白?

import * as React from "react";
import { Dropdown, DropdownMenuItemType, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { PrimaryButton } from 'office-ui-fabric-react/lib/';
export interface ParentProps {
};
export interface ParentState  {
selectedItem?: { key: string | number | undefined };
operationType?;
};
export default class ParentComponent extends React.Component<ParentProps, ParentState> {
constructor(props, context) {
super(props, context);
this.state = {
operationType: '',
};
}
addToExcel = async () => {
try {
await Excel.run(async context => {
const range = context.workbook.getSelectedRange();
range.load("address");
await context.sync();
range.values = (this.state.operationType);
});
} catch (error) {
console.error(error);
}
this.setState({
})
};
render() {
const { selectedItem } = this.state;
const options: IDropdownOption[] = [
{ key: 'blank', text: '' },
{ key: 'topLevelMake', text: 'Parents', itemType: DropdownMenuItemType.Header },
{ key: 'topLevel', text: 'TOP LEVEL' },
{ key: 'make', text: 'MAKE ITEM' },
];
return (
<div>
<Dropdown
label="Operation"
selectedKey={selectedItem ? selectedItem.key : undefined}
onChange={this._onChange}
placeholder={"Select an option"}
options={options}
styles={{ dropdown: { width: 300 } }}
/>
<p></p>
<PrimaryButton
text="Enter"
onClick={this.addToExcel}
/>
</div>
);
}
private _onChange = (e, item: IDropdownOption): void => {
this.setState({ selectedItem: item });
this.setState({ operationType: item.text })
console.log(e);
}
};

addToExcel():上尝试这样的操作

addToExcel = async () => {
try {
await Excel.run(async context => {
const range = context.workbook.getSelectedRange();
range.load("address");
await context.sync();
range.values = (this.state.operationType);
});
} catch (error) {
console.error(error);
}
this.setState({
selectedItem: {key:'blank'},
})
};

您应该在excel操作后更新您的状态。

addToExcel = async () => {
try {
await Excel.run(async context => {
const range = context.workbook.getSelectedRange();
range.load("address");
await context.sync();
range.values = (this.state.operationType); 
});
// update state after asyn operations is done
this.setState({
selectedItem:undefined
})
} catch (error) {
console.error(error);
}
};

最新更新