developer tip

'읽기 전용 <{}>'유형에 'value'속성이 없습니다.

optionbox 2020. 9. 7. 08:03
반응형

'읽기 전용 <{}>'유형에 'value'속성이 없습니다.


API의 반환 값을 기반으로 무언가를 표시 할 양식을 만들어야합니다. 다음 코드로 작업하고 있습니다.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

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

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

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value); //error here
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} /> // error here
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

다음과 같은 오류가 발생합니다.

error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.

코드에 주석을 달 았던 두 줄에이 오류가 있습니다. 이 코드는 내 것이 아니며 react 공식 사이트 ( https://reactjs.org/docs/forms.html )에서 가져 왔지만 여기서는 작동하지 않습니다.

create-react-app 도구를 사용하고 있습니다.


Component 정의 과 같이 :

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

상태 (및 props)의 기본 유형은 다음과 같습니다 {}.
구성 요소가 value상태에 있도록하려면 다음과 같이 정의해야합니다.

class App extends React.Component<{}, { value: string }> {
    ...
}

또는:

type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}

In addition to @nitzan-tomer's answer, you also have the option to use inferfaces:

interface MyProps {
  ...
}

interface MyState {
  value: string
}

class App extends React.Component<MyProps, MyState> {
  ...
}

Either is fine, as long as you're consistent.

참고URL : https://stackoverflow.com/questions/47561848/property-value-does-not-exist-on-type-readonly

반응형