reactjs - TSX/JSX 项目中的可选 JSX Props

标签 reactjs typescript jsx react-tsx

我有一个要从 JS 转换为 TS 的 React 项目。我遇到的一个问题是 TSX React 假设功能组件中定义的所有属性都是必需的 Prop 。

// ComponentA.tsx
class ComponentA extends React.Component<any, any> {
  render() {
    /* Type '{ equalWidth: true; children: Element[]; }' is not assignable to type '{ children: any; className: any; equalWidth: any; }'.
     * Property 'className' is missing in type '{ equalWidth: true; children: Element[]; }'.' */
    return <ComponentB equalWidth />
  }
}

// ComponentB.js
const ComponentB = ({ children, className, equalWidth }) => {
  return (...)
}

有没有办法向 TS 表明 JSX 组件 Prop 都是可选的?

最佳答案

一个最简单的选项是为您的可选 Prop 设置默认值。例如,如果 className 是可选的,您可以将 ComponentB.js 更改为类似这样的内容。

const ComponentB = ({ children, className="", equalWidth }) => {
  return (...)
}

另外,如果你在函数体中解构你的 props 而不是签名,TS 将不会提示输入。

const ComponentB = (props) => {
  const { children, className, equalWidth } = props;
  return (...)
}

关于reactjs - TSX/JSX 项目中的可选 JSX Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420826/

相关文章:

java - 将 React js 与现有 Java Web 应用程序一起使用

unit-testing - Chutzpah 和 Jasmine typescript 单元测试

javascript - 是否可以使用 ref 访问数组映射函数内的 React 组件?

javascript - 在 JSX/React 中通过数组映射后,首先选择 <option> 为空

reactjs - 模块解析失败: es6 react component with JSX inside . JS文件

javascript - 类型错误 : Cannot read property 'length' of undefined array shuffle in react

javascript - 显示错误以上传文件或禁用按钮

node.js - 向 Node.js 中的嵌套接口(interface)添加属性

javascript - Redux 不只是美化了全局状态吗?

javascript - 使用 Typescript 将对象的 JSON 数组转换为字符串数组