反应/打字稿:参数“道具”隐含了“任何”类型错误

新手上路,请多包涵

当我从 react-bootstrap 尝试此示例代码时,我不断收到错误消息,例如“参数‘上下文’隐含地具有‘任何’类型;“属性‘值’在类型‘只读<{}>’上不存在。”

在 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;

在 Jumbo.tsx 中:

 const Jumbo = () => (
   <FormExample />
);

原文由 newgrad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 302
2 个回答

在 _typeScript 中_,您应该安装 @types/react 并在扩展 React.Component 时需要指定 propsstate 类型。这是示例

import * as React from 'react'

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

interface State {
  ... // state types
}

class FormExample extends React.Component<Props, State> {... }

原文由 Harish 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

    constructor(props: any) {
        super(props);
    }
}

原文由 Ozgur Sahin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进