console.log 当 ReactJs 中的 onClick 时
console.log when onClick in ReactJs
我想要 onClick
元素 row
时显示 coin.id
console.log
[=17= 中的那个元素]
import React, { useState, useEffect } from "react";
import { Col, Image, Row } from "react-bootstrap";
import "./Company.scss";
// * api
import { getCoin } from "../services/api";
// *spinner
import Loader from "./Loader";
const Company = () => {
const [selectedCoin, setSelectedCoin] = useState(null);
const [coins, setCoins] = useState([]);
useEffect(() => {
const fetchAPI = async () => {
const data = await getCoin();
setCoins(data);
};
fetchAPI();
}, []);
return (
<>
{coins.length > 0 ? (
coins.map((coin) => (
<Row
className={
selectedCoin === coin.id
? "p-2 border-top d-flex align-items-center company-list-single-active"
: "p-2 border-top d-flex align-items-center company-list-single"
}
onClick={() => {
setSelectedCoin(coin.id);
}}
key={coin.id}
>
<Col xxl="2" xl="2" lg="3" md="3" sm="2" xs="2">
<Image
src={coin.image}
alt={coin.name}
className="coin-image mx-2"
fluid
/>
</Col>
<Col>
<span>{coin.name}</span>
</Col>
</Row>
))
) : (
<Loader />
)}
</>
);
};
export default Company;
screenshot project
如果您希望在 onClick
事件处理程序的匿名函数中添加另一个调用(如 console.log()
),您可以
onClick={() => {
console.log(coin.id);
setSelectedCoin(coin.id);
}}
我想要 onClick
元素 row
时显示 coin.id
console.log
[=17= 中的那个元素]
import React, { useState, useEffect } from "react";
import { Col, Image, Row } from "react-bootstrap";
import "./Company.scss";
// * api
import { getCoin } from "../services/api";
// *spinner
import Loader from "./Loader";
const Company = () => {
const [selectedCoin, setSelectedCoin] = useState(null);
const [coins, setCoins] = useState([]);
useEffect(() => {
const fetchAPI = async () => {
const data = await getCoin();
setCoins(data);
};
fetchAPI();
}, []);
return (
<>
{coins.length > 0 ? (
coins.map((coin) => (
<Row
className={
selectedCoin === coin.id
? "p-2 border-top d-flex align-items-center company-list-single-active"
: "p-2 border-top d-flex align-items-center company-list-single"
}
onClick={() => {
setSelectedCoin(coin.id);
}}
key={coin.id}
>
<Col xxl="2" xl="2" lg="3" md="3" sm="2" xs="2">
<Image
src={coin.image}
alt={coin.name}
className="coin-image mx-2"
fluid
/>
</Col>
<Col>
<span>{coin.name}</span>
</Col>
</Row>
))
) : (
<Loader />
)}
</>
);
};
export default Company;
screenshot project
如果您希望在 onClick
事件处理程序的匿名函数中添加另一个调用(如 console.log()
),您可以
onClick={() => {
console.log(coin.id);
setSelectedCoin(coin.id);
}}