【问题标题】:Why need React this code, that my code works?为什么需要 React 这段代码,我的代码可以工作?
【发布时间】:2022-01-13 14:40:04
【问题描述】:

这是我的代码

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>
  );
};

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

谢谢!

【问题讨论】:

标签: reactjs typescript frontend


【解决方案1】:

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

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>
  );
};

这将是整理此代码的最佳方法,在您的函数中不包含类型定义,而是作为一个单独的类型对象。

【讨论】:

  • 谢谢!好主意,我会用它。但我的意思是没有类型定义就没有办法做到这一点吗?
  • 不,如果你想让你的功能组件能够打字,这是你能得到的最好的。不幸的是,使用类型化组件的一个缺点是编写类型可能有点混乱......
  • 好的,非常感谢!
  • 不客气。抱歉,我无法提供更清洁的解决方案。
  • 你可以通过选择 HTMLInputElement type InputProps = { label?: ReactChild } &amp; Partial&lt;Pick&lt;HTMLInputElement, 'type'|'placeholder'&gt;&gt;987654324@ 的已定义属性使其更清晰(至少更干)
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多