我在转换器项目中工作,该项目可转换一些尺寸,例如范围,速度,温度。我想创建一个通用组件,该组件将一些值用作参数,但是我不明白它的外观。
我已经创建了一个接受米,英里等参数的组件。它需要一个包含值名称和系数的数组,该值与输入值相乘
App.tsx.
import React from 'react';
import Converter from './components/converter/Converter.component';
import './App.css';
export interface IValue {
id: number;
name: string;
coef: number;
}
const firstSel: IValue[] = [
{
id: 1, name: 'metres', coef: 1
},
{
id: 2, name: 'yards', coef: 1.094
},
{
id: 3, name: 'test3', coef: 3.234
},
{
id: 4, name: 'test4', coef: 4.55
}
];
const App: React.FC = () => {
return (
<div className="App">
<header className="App-header">
<Converter SelectValues={ firstSel } />
</header>
</div>
);
};
export default App;
Converter.component.tsx
import React, { useState } from 'react';
import StyledConverter from './Converter.styled';
import {IValue} from "../../App";
interface IConverterProps{
SelectValues: IValue[]
}
export default function Converter({SelectValues}: IConverterProps) {
const [valueLeft, setValueLeft] = useState('');
const [valueRight, setValueRight] = useState('');
const [coefLeft, setCoefLeft] = useState(1);
const [coefRight, setCoefRight] = useState(1);
function handleInputChangeLeft(event: React.ChangeEvent<HTMLInputElement>){
setValueRight(event.target.value);
setValueLeft( String(Number(event.target.value) * coefLeft));
}
function handleInputChangeRight(event: React.ChangeEvent<HTMLInputElement>){
setValueRight( String(Number(event.target.value) * coefRight));
setValueLeft(event.target.value)
}
function handleSelectChangeLeft(event: React.ChangeEvent<HTMLSelectElement>){
setCoefLeft(Number(event.target.value));
console.log('Select value', event.target.value)
}
function handleSelectChangeRight(event: React.ChangeEvent<HTMLSelectElement>){
setCoefRight(Number(event.target.value));
console.log('Select value', event.target.value)
}
return (
<StyledConverter>
<p>Converter</p>
<div className="converter__container">
<input type="number" placeholder="Input your value here" value={valueLeft} onChange={handleInputChangeRight}/>
<select name="FirstSelect" id="" onChange={handleSelectChangeLeft}>
{
SelectValues.map(({id, name, coef}) => (
<option
key={id}
value={coef}
>
{name}
</option>
))
}
</select>
<div>=</div>
<input type="number" placeholder="Input your value here" value={valueRight} onChange={handleInputChangeLeft}/>
<select name="SecondSelect" id="" onChange={handleSelectChangeRight}>
{
SelectValues.map(({id, name, coef}) => (
<option
key={id}
value={coef}
>
{name}
</option>
))
}
</select>
</div>
<p>COEF_LEFT: {coefLeft}</p>
<p>COEF_RIGHT: {coefRight}</p>
</StyledConverter>
);
}