'읽기 전용' 유형에 '값' 속성이 없습니다.< { } >
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<{}>'.
제가 코드에 코멘트한 두 줄에서 이 오류가 발생했습니다.이 코드는 제 것도 아니고, 리액트 공식 사이트(https://reactjs.org/docs/forms.html),에서 입수했는데, 여기에서는 동작하지 않습니다.
create-react-app 툴을 사용하고 있습니다.
그Component 는 다음과 같이 정의됩니다.
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
즉, 상태(및 소품)의 기본 유형은 다음과 같습니다.{}.
컴포넌트가 다음을 수행하도록 하려면value상태에서는 다음과 같이 정의할 필요가 있습니다.
class App extends React.Component<{}, { value: string }> {
...
}
또는 다음 중 하나를 선택합니다.
type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
...
}
interface MyProps {
...
}
interface MyState {
value: string
}
class App extends React.Component<MyProps, MyState> {
...
}
// Or with hooks, something like
const App = ({}: MyProps) => {
const [value, setValue] = useState<string>('');
...
};
type@nitzan-tomer의 답변과 같이, 당신이 일관성이 있는 한, 는 너무 괜찮습니다.
인터페이스 상태 또는 소품 모델을 통과하고 싶지 않은 경우 이 방법을 사용할 수 있습니다.
class App extends React.Component <any, any>
사용할 것을 권장합니다.
string only state values의 경우
export default class Home extends React.Component<{}, { [key: string]: string }> { }
string key 및 임의의 유형의 경우
export default class Home extends React.Component<{}, { [key: string]: any}> { }
모든 키/가치관에 대해
export default class Home extends React.Component<{}, { [key: any]: any}> {}
문제는 인터페이스 상태가 '값'의 적절한 변수 유형으로 대체됨을 선언하지 않았다는 것입니다.
interface AppProps {
//code related to your props goes here
}
interface AppState {
value: any
}
class App extends React.Component<AppProps, AppState> {
// ...
}
ReactJs 공식 문서에 따르면 기본 형식의 witch로 인수를 전달해야 합니다.
P = {} // default for your props
S = {} // default for yout state
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
또는 다음과 같이 사용자 고유의 유형을 정의합니다(단, exp).
interface IProps {
clients: Readonly<IClientModel[]>;
onSubmit: (data: IClientModel) => void;
}
interface IState {
clients: Readonly<IClientModel[]>;
loading: boolean;
}
class ClientsPage extends React.Component<IProps, IState> {
// ...
}
typescript 및 react whats react 성분 PS 평균
타이프 스크립트를 사용하여 반응 구성 요소를 정적으로 입력하는 방법
event.target항상 가치가 있는 것은 아닙니다.DOM 요소인 경우 올바른 유형으로 캐스팅해야 합니다.
handleChange(event) {
this.setState({value: (event.target as HTMLInputElement).value});
}
이는 상태 변수의 "올바른" 유형을 추론할 뿐만 아니라 명시적인 것이 더 나을 수 있습니다.
나의 솔루션
import React, { ChangeEvent, FormEvent } from "react";
interface NameFormProps {
}
interface NameFormState {
value: string
}
export default class NameForm extends React.Component<NameFormProps, NameFormState> {
constructor(props: any) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event: ChangeEvent<HTMLInputElement>) {
this.setState({value: event.target.value});
}
handleSubmit(event: FormEvent<HTMLFormElement>) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
언급URL : https://stackoverflow.com/questions/47561848/property-value-does-not-exist-on-type-readonly
'programing' 카테고리의 다른 글
| ng-show 및 ng-animate를 사용한 슬라이드 업/다운 효과 (0) | 2023.03.01 |
|---|---|
| C#에서 사전을 JSON 문자열로 변환하려면 어떻게 해야 하나요? (0) | 2023.03.01 |
| 색인 페이지의 WordPress wp_title 공백 (0) | 2023.03.01 |
| 스프링 3 주석을 사용하여 심플한 공장 패턴 구현 (0) | 2023.03.01 |
| 루비의 JSON 파일에서 구문 분석 및 중첩된 해시에서 숫자 추출 (0) | 2023.03.01 |