gpt4 book ai didi

javascript - 我如何在 React TypeScript 中引用文档?

转载 作者:行者123 更新时间:2023-12-05 06:07:40 26 4
gpt4 key购买 nike

我想在我的一个条件函数中执行此操作,但它完全出错了。即使我将它分配给一个变量,它也会说“找不到命名空间‘文档’”

document.getElementById("dropdown").selectedIndex = "1";

当我将它放入我的函数时,它说 Object 可能为 null,那么我如何在 React tsx 文件中引用它?

我有一个 select 语句,我需要根据某些条件动态选择默认值。如果这些条件为真,那么它将运行此文档选择器以选择指定值的索引。我只需要找到一种方法来运行一个选择此 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]);

最佳答案

您所面临的问题通过了解 React unidirectional data flow 得到解决.您的真理来源应该始终来自上方。

更具体地说,您不会直接读取或写入您的 #select 元素,而是您拥有它的状态值,这将是您的真实来源:

const MyComponent = ({ groups }) => {
const [selectedIndex, setSelectedIndex] = useState(0) // or the default value

/**
* In here, you'll let react know that you want some code to run, when
* this property changes in the outside world
*/
useEffect(() => {
if (groups.includes('IT') || groups.includes('Sales')) {
setSelectedIndex(1)
}
}, [groups]);

// ...

return (
<Select
value={selectedIndex}
....other props...
>
... children
</Select>
)
}

基本上,您不使用 document.getElementId

关于javascript - 我如何在 React TypeScript 中引用文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65359801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com