首页 > 解决方案 > 我如何在反应打字稿中引用文档?

问题描述

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

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]);

标签: javascriptreactjstypescriptreact-typescript

解决方案


你所面临的问题是通过理解React 单向数据流来解决的。你的真理来源应该永远来自上面。

更具体地说,您不会直接读取或写入您的#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.


推荐阅读