【问题标题】:Is there any way to write the function without explicitly using defaultProps in react function component?有没有办法在反应函数组件中不显式使用 defaultProps 来编写函数?
【发布时间】:2021-07-30 17:03:15
【问题描述】:

我有一个类似的组件

import React, { ReactNode } from "react";

const defaultContainerProps = {
  heading: <h1>Default Heading</h1>,
};

function App({
  children,
  heading,
}: {
  children: ReactNode;
} & typeof defaultContainerProps) {
  return (
    <div>
      <h1>{heading}</h1>
      {children}
    </div>
  );
}

App.defaultProps = defaultContainerProps;

export default App;

它工作得很好,但是在 es6 中可以直接在函数参数中给出默认道具,所以我像这样更新了我的函数

const defaultContainerProps = {
  heading: <h1>Default Heading</h1>,
};

function App({
  children,
  heading = defaultContainerProps.heading,
}: {
  children: ReactNode;
} & typeof defaultContainerProps) {
  return (
    <div>
      <h1>{heading}</h1>
      {children}
    </div>
  );
}

但是当我使用这个组件时,它希望我给标题道具 错误:'{ children: string; 类型中缺少属性 'heading' }' 但在类型 '{ 标题:JSX.Element; 中是必需的; }'。

使用该组件的主文件

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App>Foo</App> // Property 'heading' is missing in type '{ children: string; }' but required in type '{ heading: JSX.Element; }'.
  </React.StrictMode>,
  document.getElementById("root")
);

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    要使用默认值,方法参数中的值需要为空,并且参数的类型不允许为空。要使其正常工作,请使用 Partial 实用程序类型(它使所有内容都可以为空)

    function App({ children,
     heading = defaultContainerProps.heading,}: {
     children: ReactNode;} & Partial<typeof defaultContainerProps>) 
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2014-04-17
      相关资源
      最近更新 更多