【问题标题】:concise and readable syntax for props in a react component in typescript打字稿中反应组件中道具的简洁易读语法
【发布时间】:2020-07-26 03:47:24
【问题描述】:

所以如果你声明一个 React.FC ,那么你就可以做一个类型声明,从而传递它的 props :

const FuntionalComponent: React.FC<personType> = ({ id, nationality, name, familyName, age, selected }) =>

    <div>
       ...directly html
    </div>

export default FuntionalComponent;

但是你不能在那里声明任何方法或使用钩子(我还没有找到方法)

然后是React.Component 类型:

class Component extends React.Component<{}, {Stateproperty: string}>{

  constructor(){
  }

  hook(){
  }

  method(){
  }

  render() {
    return (
      <div>
         ...html finally
      </div>
    )
  }
}

export default component;

如您所见,我可以传递状态,但不能传递道具。

如果我尝试这样的事情:

class Component extends React.Component<{propsProperty: Array}, {Stateproperty: string}>{

然后将我的 propsProperty 添加到我的 html 中:

<Component propsProperty={thisArray} />

然而,他们错误地输入了以下条目:

TS2322: 类型 '{ propsProperty: any; }' 不可分配给类型 'IntrinsicAttributes & { children?: ReactNode; }'。财产 类型“IntrinsicAttributes & { children?”上不存在“tankData”: 反应节点; }'。

这些教程似乎表明没有其他方法可以声明组件:

https://riptutorial.com/reactjs/example/25321/declare-default-props-and-proptypes https://medium.com/@cristi.nord/props-and-how-to-pass-props-to-components-in-react-part-1-b4c257381654

我发现这篇关于 React 中的 TypeScript 错误的文章: https://medium.com/innovation-and-technology/deciphering-typescripts-react-errors-8704cc9ef402,但这不是我的问题。

我也试过这个解决方案:https://stackoverflow.com/a/47395464/4770754。尽管这显然不是同一个问题,但似乎有些接近,但没有帮助。

React 文档没有帮助,因为它们忽略 TypeScript 并且不可读。

我需要一种既简洁又尊重 TypeScript 并允许在类体内同时使用道具和方法的方法。这根本不存在吗?

【问题讨论】:

    标签: reactjs typescript react-component


    【解决方案1】:

    但是你不能在那里声明任何方法或使用钩子(我还没有找到方法)

    声明 FC 的标准方法是:

    type ComponentProps = {
      id: string, 
      nationality: string, 
      ...
    }
    
    const MyComponent: React.FC<ComponentProps> = ({
      id, 
      nationality, 
      ...rest
      }: ComponentProps) => {
      
      const someMethod = () => {
        console.log('I am console logging');
      }
    
    
      return(
        <div>
          {/* HERE YOU WILL RENDER STUFF */}
        </div>
      )
    }
    

    请注意,在上面我解构了实例化的道具,以便可以直接在组件中使用idnationality

    在您熟悉上述内容之前,我认为您无需过多担心语法突出显示。

    【讨论】:

    • 找不到名称“构造函数”。为什么我不能放方法?
    • 抱歉,我的示例在someMethod 之前缺少const。如果能解决你的问题,你能试试吗?至于为有状态的 React 组件保留的 constructor - 它不以相同的方式存在于功能组件中,但是您应该能够使用例如重复相同的功能。 useEffect 钩子。
    • 什么?如何?我不明白。
    • 例如,在第一次渲染时,您可以显示一些加载渲染。一旦安装,所有useEffect(() =&gt; {...}, []) 将被调用。此模式可用作construct 的替代品。
    • 我收到运行时错误:Line 10:27: React Hook "useEffect" is called in function "carousel: React.FC" which is neither a React function component or a custom React Hook 为什么?
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2020-04-08
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2020-08-21
    • 2016-08-13
    • 2018-10-26
    相关资源
    最近更新 更多