[英]Unable to get the key value of the item clicked in react hooks
During on click on each boxes I would like to get the tags
of the corresponding box.在单击每个框时,我想获取相应框的
tags
。 But while console log the print tags, it is displaying as undefined.但是当控制台记录打印标签时,它显示为未定义。 I have tried both cases like
e.currentTarget.tags
and e.target.tags
, but still not getting the correct result.我已经尝试过
e.currentTarget.tags
和e.target.tags
两种情况,但仍然没有得到正确的结果。 Could someone please help ?有人可以帮忙吗?
Demo link:演示链接:
https://codesandbox.io/s/serene-elgamal-lyyih?file=/src/App.js:87-1914 https://codesandbox.io/s/serene-elgamal-lyyih?file=/src/App.js:87-1914
const blogData = [
{
id: 1,
title: "Cypress tests",
description: "Add the E2E cypress UI tests",
createddate: "19 September 2020",
tags: "cypress"
},
{
id: 2,
title: "Jmeter tests",
description: "Performance test using Jmeter tool",
createddate: "15 August 2020",
tags: ["jmeter", "performance"]
},
{
id: 3,
title: "Basic Unix commands",
description: "Learn basic unix commands in git bash",
createddate: "10 July 2020",
tags: "unix"
},
{
id: 4,
title: "Postman",
description: "Api testing using postman",
createddate: "1 June 2020",
tags: ["postman", "api"]
}
];
export default function App() {
const [searchResults, setSearchResults] = useState([]);
const [showColor, setShowColor] = useState("");
const [findTag, setFindTag] = useState("");
useEffect(() => {
setSearchResults(blogData);
}, [blogData]);
const randomizedHex = (e) => {
setFindTag(e.currentTarget.tags);
console.log("Print tag:", findTag);
const randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
setShowColor(randomColor);
};
return (
<div className="App">
<div className="wrap">
{searchResults.map((blog) => (
<article onClick={randomizedHex} className="equalBox">
<section>
<span key={blog.id}> {blog.id} </span>
</section>
<section>
<div key={blog.tags}>{blog.tags}</div>
</section>
</article>
))}
</div>
</div>
);
}
The code needs to pass the blog
object to the callback:代码需要将
blog
对象传递给回调:
const randomizedHex = (blog) => {
setFindTag(blog.tags);
console.log("Print tag:", findTag);
const randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
setShowColor(randomColor);
};
return (
<div className="App">
<div className="wrap">
{searchResults.map((blog) => (
<article onClick={() => { randomizedHex(blog); }} className="equalBox">
<section>
<span key={blog.id}> {blog.id} </span>
</section>
<section>
<div key={blog.tags}>{blog.tags}</div>
</section>
</article>
))}
</div>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.