useState / props / memo / propTypes / useEffect
inputė valueė ëģėëĨž í ëđíęģ onChange íĻėė ėíī ę°ė§ë íīëđ inputė event.target.valueė ę°ėī inputė valueę° ëëëĄ íėŽ ę·ļ ę°ėī ëģíí ëë§ëĪ ėŧīíŽëíļę° ëĶŽë ëë§ ëėī íëĐīėī ëĪė ę·ļë Īė§ëëĄ íëĪ.
import { useState } from "react";
function App() {
const [todo, setTodo] = useState("");
const [todos, setTodos] = useState([]);
const onChange = (event) => setTodo(event.target.value);
const onSubmit = (event) => {
event.preventDefault();
if (todo === "") {
return;
}
setTodo(""); // ėīęąļ ëĻžė ėėąíīë
setTodos(currentArray => [todo, ...currentArray]); // ėŽęļ°ė todoę° ""ë ėëëĪ. (âĩ ėė§ ëĶŽë ëë§ x)
};
return (
<div>
<form onSubmit={onSubmit}>
<input onChange={onChange} value={todo} />
<button>ėķę°</button>
</form>
<ul>
{todos.map((todo, index) => <li key={index}>{todo}</li>)}
</ul>
</div>
);
}
export default App;
( ė―ë ėąëĶ°ė§ )
ė ėļęģ ėíļ íí ėĒ
ëĨëĨž ëŠĻë ę°ė ļėĻëĪ.
ííëĨž ė íí í ėĄėëĨž ė
ë ĨíëĐī USD coin ę°ėđëĨž ëģīėŽėĪëĪ.
// App.js
import { useState, useEffect } from "react";
import Input from "./Input";
function App() {
const [loading, setLoading] = useState(true);
const [coins, setCoins] = useState({});
const [amount, setAmount] = useState(0);
const [selectValue, setSelectValue] = useState("select");
const [disabled, setDisabled] = useState(true);
const onInputValueChange = (event) => setAmount(event.target.value);
const onSelectValueChange = (event) => {
setSelectValue(event.target.value);
event.target.value === "select" ? setDisabled(true) : setDisabled(false);
setAmount(0);
};
useEffect(() => {
fetch("https://api.coinpaprika.com/v1/tickers")
.then((response) => response.json())
.then((json) => {
setCoins(json);
setLoading(false);
});
}, []);
return (
<div>
<h1>Coin Traker {loading ? "" : `(${coins.length})`}</h1>
{loading ? (
<h3>ëĄëĐ ėĪė
ëëĪ...</h3>
) : (
<select onChange={onSelectValueChange} value={selectValue}>
<option value="select">Select the currency</option>
{coins.map((coin) => (
<option
value={coin.quotes.USD.price}
key={coin.id}
>{`${coin.name}(${coin.symbol})`}</option>
))}
</select>
)}
<br />
<Input onChange={onInputValueChange} value={amount} disabled={disabled} />
<br />
<Input
value={selectValue === "select" ? 0 : amount * selectValue}
disabled={disabled}
readOnly={true}
/>
</div>
);
}
export default App;
// Input.js
import PropTypes from "prop-types";
function Input({ onChange, value, disabled, readOnly }) {
return (
<input
onChange={onChange}
value={value}
disabled={disabled}
readOnly={readOnly}
></input>
);
}
Input.propTypes = {
onChange: PropTypes.func,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
disabled: PropTypes.bool.isRequired,
readOnly: PropTypes.bool,
};
export default Input;