react/typescript: Parameter 'props' implic

2020-06-09 01:57发布

When I try this sample code from react-bootstrap, I keep getting errors such as " Parameter 'context' implicitly has an 'any' type; "Property 'value' does not exist on type 'Readonly<{}>'."

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

in Jumbo.tsx:

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

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-06-09 02:40

in type script you need to specify the type of props you are going to send or it takes the default type defined tin @types/react. if you dont want to specify any type then explicitly ask the component to expect state and props of 'any' type.

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

the first type argument is for defining the type of props you are expecting , the other is for type of state of the component.

查看更多
虎瘦雄心在
3楼-- · 2020-06-09 02:42

Specifying the type of the constructor parameter resolved this issue in my case.

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

    constructor(props: any) {
        super(props);
    }
}
查看更多
够拽才男人
4楼-- · 2020-06-09 02:42

I just got this error on a functional component.

In order to get information such as props.children as well as custom props, you should do the following.

import { FunctionComponent } from 'react';

const Layout: FunctionComponent<{ hello: string }> = props => (
  <div style={layoutStyle}>
    <Header />
    {props.hello}
    {props.children}
  </div>
);
查看更多
叼着烟拽天下
5楼-- · 2020-06-09 02:47

In typeScript you should install @types/react and while extending the React.Component you need to specify the props and state types. Here is the example

import * as React from 'react'

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

interface State {
  ... // state types
}

class FormExample extends React.Component<Props, State> {... }
查看更多
登录 后发表回答