简体   繁体   English

我如何在反应 typescript 中参考文档?

[英]How do i reference document in react typescript?

I wanna do this in one of my conditional functions, but it's completely erroring out.我想在我的一个条件函数中执行此操作,但它完全出错了。 Even if I assign it to a variable it says "cannot find namespace 'document'"即使我将它分配给一个变量,它也会说“找不到命名空间'文档'”

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

And when I put that in my function it says Object is possibly null, so how do I reference this in a react tsx file?当我把它放在我的 function 中时,它说 Object 可能是 null,那么我如何在反应 tsx 文件中引用它?

I have a select statement that I need to dynamically select the default value based on some conditions.我有一个 select 语句,我需要根据某些条件动态 select 的默认值。 If those conditions are true, then it will run this document selector to select the index of the specified value.如果这些条件为真,那么它将运行此文档选择器到 select 指定值的索引。 I just need to find a way to run a function that selects the default value of this select statement though, that's my goal我只需要找到一种方法来运行 function 选择此 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>

And then this is the function that creates those menu items, as well as the conditionals to set the default value:然后这是创建这些菜单项的 function,以及设置默认值的条件:

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

The problem you're facing is solved by understanding React unidirectional data flow .你所面临的问题是通过理解React 单向数据流来解决的。 Your source of truth should come from above, always.你的真理来源应该永远来自上面。

In more concrete words, you wouldn't read or write directly to your #select element, but instead you'd have an state value for it, which would be your source of truth:更具体地说,您不会直接读取或写入#select元素,而是会为它提供一个 state 值,这将是您的事实来源:

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>
  )
}

Basically, you don't use document.getElementId .基本上,您不使用document.getElementId

You'll need to tell typescript that you're creating a browser app via tsconfig.json .您需要通过tsconfig.json告诉 typescript 您正在创建浏览器应用程序。 You can add a lib property with the value dom .您可以添加一个值为domlib属性。 An example:一个例子:

{
  "compilerOptions": {
    "lib": ["es5", "es6", "dom"], // <-- here
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "moduleResolution": "node",
    "jsx": "react"
  },
  "include": ["./src/**/*"]
}

This will allow typescript to recognize the document as a valid interface.这将允许 typescript 将document识别为有效接口。

Once that's out of the way, an idiomatic approach at selecting DOM nodes in React function components is with useRef .一旦解决了这个问题,在 React function 组件中选择 DOM 节点的惯用方法是使用useRef

import React, { useRef, useEffect } from 'react'

const SomeComponent = ({ innerRef }) => (
   <div ref={innerRef}>some div</div>
)

const ParentComponent = () => {
   const ref = useRef()

   useEffect(() => {
     if(ref.current) {
        console.log(ref.current.selectedIndex)
     }
   }, [ref.current])
   return <SomeComponent innerRef={ref} />
}

A ref doesn't have to be passed from a parent. ref 不必从父级传递。 It can be used in the same doc.它可以在同一个文档中使用。 I just added that in case your use case required it.我只是补充说,以防您的用例需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript:如何在本文档中引用另一个文档的字段? - Typescript: How can I reference another document's field inside of this document? 如何在 TypeScript 中使用 JSDoc 记录“提供者模式”功能? - How do I document "provider-pattern" functions with JSDoc in TypeScript? 如何使用TypeScript和DefinitelyTyped引用jQuery选择器? - How do I reference a jQuery selector using TypeScript and DefinitelyTyped? 如何将 Firestore 文档引用存储为 nextjs 中的字段? - How do I store a Firestore document reference as a field from nextjs? 如何在 React TypeScript 中输出过滤后的待办事项列表 - how do I output the filtered todo list in React TypeScript 如何在 typescript 中的 onChange 和 onClick 函数中添加类型 - How do I add type to onChange & onClick functions in typescript react 如何在列表中获取数组? 使用 React.JS,Typescript - How do I get array in the list? with React.JS, Typescript 如何使用 typescript 从 React 中的状态创建新的 object? - How do I create a new object from states in React with typescript? 如何在 React 和 Typescript 中将组件作为道具传递? - How do I pass a component as a prop in React and Typescript? 如何在反应 typescript 中呈现本地存储中的数据? - How do i render data from local storage in react typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM