简体   繁体   English

你如何在反应 typescript 中根据需要标记道具?

[英]How do you mark a prop as required in react typescript?

I am trying to mark a prop as a required prop in a react typescript application, how can I do that?我试图在反应 typescript 应用程序中将道具标记为必需道具,我该怎么做? Using react with js, one chains isRequired keyword on the type.使用 React with js,在类型上使用一个链isRequired关键字。 How can i do this with ts?我怎么能用 ts 做到这一点?

// Here is my typescript code:

interface Props {
  /** Message to display */
  message: string;
}

const defaultProps: Props = {
  message: 'World',
};
/** My first reusable component */
function HelloWorld({ message }: Props) {
  return <div>Hello {message}</div>;
}

HelloWorld.defaultProps = defaultProps;

Here is the jsx I am trying to reproduce这是我试图重现的 jsx

import PropTypes from 'prop-types';

function HelloWorld({message}) {
  return <div>Hello {message}</div>
}

HelloWorld.propTypes = {
  message: PropTypes.string.required
};

HelloWorld.defaultProps = {
  message: 'World'
};

export default HelloWorld;

I think you have to explicitly specify output type for HelloWorld function我认为您必须为HelloWorld function 明确指定 output 类型

function HelloWorld({ message }: Props): React.SFC<Props> {
  return <div>Hello {message}</div>;
}

or或者

const HelloWorld: React.SFC<Props> = ({ message }) => {
  return <div>Hello {message}</div>;
}

I don't really get what you mean?我真的不明白你的意思? If you define an interface without optional fields, all of them are required by default?如果你定义一个没有可选字段的接口,默认都是必填的? Yout don't need extra type checking.你不需要额外的类型检查。

暂无
暂无

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

相关问题 如何仅在具有 Typescript 的容器组件的上下文中使用 React 道具? - How do I make a React prop only required when used in the context of a Container component with Typescript? 你如何为 React 中必需道具的可选子属性默认默认道具? - How do you default default props for an optional child property of a required prop in React? 如何在 React 和 Typescript 中将组件作为道具传递? - How do I pass a component as a prop in React and Typescript? Typescript React:使用传递给同一组件的另一个道具有条件地将道具标记为可选或强制性 - Typescript React: Conditionally mark prop to optional or mandatory using another prop passed to same component 如何将 ReactNode 定义为打字稿反应组件的道具? - How to Define ReactNode as a prop for a typescript react component? 如何在组件(React + TypeScript)中输入链接属性? - How to type link prop in component (React + TypeScript)? 参考 Typescript 中的道具在反应 - Ref as prop in Typescript in react 当使用Route render prop而不是Route component prop时,如何访问react-router-dom 4中的url args? - How do you access url args in react-router-dom 4 when using Route render prop instead of Route component prop? 你如何配置一个反应应用程序来使用 typescript? - How do you configure a react app to use typescript? 你如何将支柱传递到所有反应路线? (动态更改标题) - How do you pass a prop to all react routes? (Change title dynamically)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM