react/typescript:参数'props'隐含有'any'类型错误

new*_*rad 7 twitter-bootstrap typescript reactjs redux

当我从react-bootstrap尝试这个示例代码时,我不断收到错误,例如"参数'上下文'隐含地具有'任意'类型;"类型'Readonly <{}>'上不存在属性'值'."

在form.tsx中:

class FormExample extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    };
  }

  getValidationState() {
    const length = this.state.value.length;
    if (length > 10) return 'success';
    else if (length > 5) return 'warning';
    else if (length > 0) return 'error';
    return null;
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  render() {
    return (
      <form>
        <FormGroup
          controlId="formBasicText"
          validationState={this.getValidationState()}
        >
          <ControlLabel>Working example with validation</ControlLabel>
          <FormControl
            type="text"
            value={this.state.value}
            placeholder="Enter text"
            onChange={this.handleChange}
          />
          <FormControl.Feedback />
          <HelpBlock>Validation is based on string length.</HelpBlock>
        </FormGroup>
      </form>
    );
  }
}

export default FormExample;
Run Code Online (Sandbox Code Playgroud)

在Jumbo.tsx:

const Jumbo = () => (
   <FormExample />
);
Run Code Online (Sandbox Code Playgroud)

Har*_*ish 21

在typeScript中你应该安装@ types/react,在扩展React.Component时你需要指定props和state类型.这是一个例子

import * as React from 'react'

interface Props {
  ... // your props validation
}

interface State {
  ... // state types
}

class FormExample extends React.Component<Props, State> {... }
Run Code Online (Sandbox Code Playgroud)

希望它会对你有所帮助

  • 或者很容易在 tsconfig.json 中将 noImplicitAny 设置为 false (9认同)
  • @bbsimonbb“轻松”关闭 TS 功能并不是一个解决方案,这是一个糟糕的建议,有很多副作用,从该评论中完全不清楚。如果必要的话,我建议在代码中进行例外处理。关闭严格检查会将类型安全性从 100% 更改为 ???%。不是很好。 (4认同)
  • @帕维尔·纳扎罗夫 不!这违背了 TS 的目的。 (3认同)

Ozg*_*hin 13

在我的例子中,指定构造函数参数的类型解决了这个问题.

class Clock extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它是否违背了 TypeScript 严格类型的目的? (6认同)
  • 如果组件没有接收任何 props,最好说 props: {} 而不是 any (2认同)

Ste*_*aul 7

我刚刚在功能组件上收到此错误。

为了获取诸如props.children自定义道具之类的信息,您应该执行以下操作。

import { FunctionComponent } from 'react';

const Layout: FunctionComponent<{ hello: string }> = props => (
  <div style={layoutStyle}>
    <Header />
    {props.hello}
    {props.children}
  </div>
);
Run Code Online (Sandbox Code Playgroud)