我有一个要从 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/