为什么需要 React 这段代码,我的代码可以工作?

Why need React this code, that my code works?

这是我的代码

const Input = props => {
  return (
    <React.Fragment>
      <label>{props.label}</label>
      <input 
        className="input" 
        type={props.type} 
        placeholder={props.placeholder}
      ></input>
    </React.Fragment>
  );
};

我想从我的应用程序的其他组件接收数据。但它只适用于第一次 props 调用后的另一行代码:

    const Input = (props: { label: boolean | React.ReactChild | React.ReactFragment | React.ReactPortal | null | undefined; type: string | (string & {}) | undefined; placeholder: string | undefined; }) => {
  return (
    <React.Fragment>
      <label>{props.label}</label>
      <input 
        className="input" 
        type={props.type} 
        placeholder={props.placeholder}
      ></input>
    </React.Fragment>
  );
};

有没有办法让这段代码看起来更漂亮?

谢谢!

我假设您对必须声明输入字段类型的部分的外观感到沮丧。

const Input = (props: { label: boolean | React.ReactChild | React.ReactFragment | React.ReactPortal | null | undefined; type: string | (string & {}) | undefined; placeholder: string | undefined; }) => {

如果我是你,我会做的是在你的功能组件之上创建一个名为 InputProps 的新 Typescript 类型并将其设置为该类型,这样你的新代码将如下所示:

// new stuff here
type InputProps = {
  label: boolean | React.ReactChild | React.ReactFragment | React.ReactPortal | null | undefined;
  type: type: string | (string & {}) | undefined;
  placeholder: string | undefined;
}

    const Input = (props: InputProps) => {
  return (
    <React.Fragment>
      <label>{props.label}</label>
      <input 
        className="input" 
        type={props.type} 
        placeholder={props.placeholder}
      ></input>
    </React.Fragment>
  );
};

最好不要在函数中定义类型,而是将其作为单独的类型对象来整理此代码。