반응형
책보고 코딩 했는데 오류 발생.
React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
<Calc x={x} y={y} oper={oper} />
-----------------------------------------
type CalcPropsType = {
x: number;
y: number;
oper: string;
};
const Calc = (props: CountryListPropsType) => {
let result: number = 0;
switch(props.oper) {
case "+":
result = props.x + props.y;
break;
case "*":
result = props.x * props.y;
break;
default:
result = 0;
};
return (
<div>
<h3>연산방식 : {props.oper}</h3>
<hr/>
<div>
{props.x} {props.oper} {props.y} = {result}
</div>
</div>
);
};
어쨰든 왠지.. 하나로 넘겨 보내야 하지 않을 까? 해서
src\QuickStart\TopPage.tsx
import { useState } from "react";
import Calc from './Calc';
import {CountryListPropsType, CalcTypes} from './Calc';
const TopPage = () => {
const [calcProps, setCalcProps] = useState<CalcTypes>(
{ x: 100, y: 200, oper:"+" }
);
/*
const [x, setX] = useState<number>(100);
const [y, setY] = useState<number>(200);
const [oper, setOper] = useState<string>("+");
*/
/*
const x= 100;
const y= 200;
const oper ="+";
*/
return (
<Calc caldata={calcProps} />
);
};
export default TopPage;
src\QuickStart\Calc.tsx
import React from 'react';
export type CountryListPropsType = {
item: CalcTypes;
};
export type CalcTypes = {
x: number;
y: number;
oper: string;
};
const Calc = (props: CountryListPropsType) => {
let item = props.item;
let result: number = 0;
switch(item.oper) {
case "+":
result = item.x + item.y;
break;
case "*":
result = item.x * item.y;
break;
default:
result = 0;
};
return (
<div>
<h3>연산방식 : {item.oper}</h3>
<hr/>
<div>
{item.x} {item.oper} {item.y} = {result}
</div>
</div>
);
};
export default Calc;
연산방식 : +
100 + 200 = 300
반응형
'개발정보' 카테고리의 다른 글
React : Parameter 'draft' implicitly has an 'any' type. (0) | 2023.07.07 |
---|---|
React, some 메서드로 배열 검사하기 (0) | 2023.07.07 |
Cannot find module 'style-components' or its corresponding type declarations. (0) | 2023.07.05 |
크롬 모바일모드 커서 사라짐 (0) | 2023.07.04 |
visual studio code github 연동 (0) | 2023.07.02 |