【发布时间】:2020-12-18 15:37:00
【问题描述】:
我想在我的一个条件函数中执行此操作,但它完全出错了。即使我将它分配给一个变量,它也会说“找不到命名空间'文档'”
document.getElementById("dropdown").selectedIndex = "1";
当我把它放在我的函数中时,它说 Object 可能为 null,那么我如何在 react tsx 文件中引用它?
我有一个选择语句,我需要根据某些条件动态选择默认值。如果这些条件为真,那么它将运行此文档选择器以选择指定值的索引。我只需要找到一种方法来运行一个选择此 select 语句的默认值的函数,这就是我的目标
<Select
value={action}
variant="outlined"
classes={{ select: classes.selectOutlined }}
id="dropdown"
displayEmpty
inputProps={{ 'aria-label': 'Action' }}
onChange={(event) => handleActionChange(event.target.value as string)}
>
<MenuItem value="Action" disabled>
Choose an Action
</MenuItem>
{actions.map((action) => {
return <MenuItem key={action.text} value={action.text}>{action.text}</MenuItem>
})}
</Select>
然后这是创建这些菜单项的函数,以及设置默认值的条件:
const actions = useMemo(() => {
let allActions: Array<{ text: string, value: string }> = [
{ text: 'Notify SME for Review', value: 'sme' },
{ text: 'Return for Review', value: 'review' },
{ text: 'Notify Sales for Review', value: 'notify' },
{ text: 'Release to Agent', value: 'release' }
];
if (groups.includes('SME')) {
allActions = [{ text: 'Notify Sales for Review', value: 'notify' }, { text: 'Return for Review', value: 'review' },]
} else if (groups.includes('IT')) {
allActions = [{ text: 'Notify SME for Review', value: 'sme' },]
} else if (groups.includes('Sales')) {
allActions = [{ text: 'Release to Agent', value: 'release' }]
}
// This will select the second item in the select element when it's IT or Sales
if (groups.includes('IT') || groups.includes('Sales')) {
const dropdown = document.getElementById('dropdown')!.selectedIndex = "1";
}
return allActions;
}, [groups]);
【问题讨论】:
-
请不要以这种方式改变 DOM 元素属性。要对 DOM 元素进行操作,请使用 ReactRef
-
直接对DOM元素进行操作的场景很少,但这不是其中之一。请改为了解 React 的单向数据流。
标签: javascript reactjs typescript react-typescript