如何将其余的props传递给react组件,同时在界面中定义所需的props

IT技术 reactjs typescript
2021-05-19 15:51:36

那么这是同样的问题,还是我只是遗漏了什么?

import * as React from 'react';

interface Props {
    value: string;
}

const MyComponent = (props: Props) => {
    const { value, ...rest } = props;

    return (
        <input {...rest} type="text" value={value} />
    );
}

interface ParentState {
    searchText: string;
}

class ParentComponent extends React.Component<{}, ParentState> {
    state: ParentState = {
        searchText: ''
    };

    onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => {
        this.setState({
            searchText: e.currentTarget.value
        });
    }

    render() {
        const { searchText } = this.state;

        return (
            <div>
                <h2>Some Text</h2>
                <MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/> 
// Errors here
            </div>
        )
    }
}

export default ParentComponent

当我在接口中定义 MyComponent 的 props 时,我收到以下错误:

错误 TS2339:属性“onChange”在类型“IntrinsicAttributes & Props”上不存在。

但是,如果我将 props 类型更改为 any,它就可以正常编译。

const MyComponent = (props: any) => {

是否可以在接口中定义 props 以便有特定的 props 是必需的,但也允许传入额外的 props 这样我就不必显式地将它们添加到接口中?

我使用的是 TypeScript 2.3.4 和 React 15.5.4。

2个回答

您可以通过向界面添加字符串索引签名避免过多的属性/属性检查

interface Props {
    value: string;

    // This is a string index signature.
    // This means that all properties in 'Props' are assignable to
    // the empty object type ({})
    [propName: string]: {};
}

您也可以编写,[propName: string]: any但这通常会降低使用MyComponent本身的安全性

如果要将input元素的所有属性转发MyComponent到 props 中MyComponent,可以查找哪些 props input(例如,在 VSCode 中,在input标签上使用 go to definition )。

interface IntrinsicElements {
   ....
   input: React.DetailedHTMLProps<React.InputHTMLAttributes<>, HTMLInputElement>;
   ....
}

我们可以将其React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>用作 props 的基本类型,我们将获得input. 由于DetailedHTMLProps 只是添加refReact.InputHTMLAttributes<HTMLInputElement>我们可以React.InputHTMLAttributes<HTMLInputElement>用作基本接口来获取input除以下属性之外的所有属性ref

import * as React from 'react'

interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
    value: string;
}

const MyComponent = (props: Props) => {
    const { value, ...rest } = props;

    return (
        <input {...rest} type="text" value={value} />
    );
}

// Usage
interface ParentState  { searchText :string }
class ParentComponent extends React.Component<{}, ParentState> {
  state: ParentState = {
      searchText: ''
  };

  onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => {
      this.setState({
          searchText: e.currentTarget.value
      });
  }

  render() {
      const { searchText } = this.state;

      return (
          <div>
              <h2>Some Text</h2>
              <MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/> 
          </div>
      )
  }
}

export default ParentComponent