ReactJS:通过onChange/onClick从映射中传递ID



如何使用onChange或onClick从点击的项目中获取id,我想推送用户点击的特定项目。这完全是错误的方式吗?

我的代码:

import React, { useState } from "react";
import "antd/dist/antd.css";
import { Select } from "antd";
import { useHistory } from "react-router-dom";

function EventsSection() {
const { Option } = Select;
const history = useHistory();
const anarray = [
{ name: "obama", address: "usa", id: "81" },
{ name: "obama", address: "usa", id: "86" },
{ name: "putin", address: "russia", id: "91" },
{ name: "erdogan", address: "turkey", id: "31" },
{ name: "jebordoq", address: "alien", id: "29" },
];
const changed = (event: any) => {
history.push(`/Detail/${event.id}`);
};
return (
<section>

<Select
className="senderId"
style={{ width: "100%" }}
placeholder="Hide Me"
onChange={changed}
open={true}
listHeight={350}
>
{anarray.map((item, idx) => (
<Option
style={{ width: "100%", height: "100%" }}
className="options"
key={idx}
value={item.id}
>
{item.name}
<br></br>
{item.address}
<br></br>
</Option>
))}
</Select>
</section>
);
}
export default EventsSection;

问我是否需要

以下是功能代码:

import React from "react";
import { Select } from "andt";
import {
BrowserRouter as Router,
Switch,
Route,
useParams,
useHistory
} from "react-router-dom";
function EventsSection() {
const { Option } = Select;
const history = useHistory();
const anArray = [
{ name: "obama", address: "usa", id: "81" },
{ name: "obama", address: "usa", id: "86" },
{ name: "putin", address: "russia", id: "91" },
{ name: "erdogan", address: "turkey", id: "31" },
{ name: "jebordoq", address: "alien", id: "29" }
];
const changeHandler = (name) => {
history.push(`/Detail/${name}`);
};
return (
<section>
<Select
className="senderId"
style={{ width: "100%" }}
placeholder="Hide Me"
onChange={changeHandler}
open={true}
listHeight={350}
>
{anArray.map((item, idx) => (
<Option
style={{ width: "100%", height: "100%" }}
className="options"
key={idx}
value={item.name}
>
{item.name}
<br></br>
{item.address}
<br></br>
</Option>
))}
</Select>
</section>
);
}
function SlugHandler() {
let { slug } = useParams();
return <h3>I am {slug}!</h3>;
}
function BasicExample() {
return (
<Router>
<Switch>
<Route exact path="/">
<EventsSection />
</Route>
<Route path="/Detail/:slug">
<SlugHandler />
</Route>
</Switch>
</Router>
);
}
export default BasicExample;

如果您想保留id,只需替换Options的值prop,即value={item.id},也可以从句柄函数中替换它(如果这是您特别想要的(。

这里是功能代码沙盒链接:

https://codesandbox.io/s/quizzical-thunder-nl2w5

您可以从事件处理程序函数接收的事件对象中获取元素的id。尝试使用:

const changed = (event: any) => {
history.push(`/Detail/${event.target.id}`); 
};

最新更新