Как и при любом другом вызове функции, вы должны передать информацию в качестве аргумента:
Parent.tsx
:
const Parent = () => {
const [someState, setSomeState] = useState("");
const toggleState = (e: React.MouseEvent, title: string) => {
setSomeState(title);
}
return (
<Child toggleState={(e, title) => toggleState(e, title)} items={items}/>
)
// −−−−−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−−−−−−−−^^^^^
}
Child.tsx
:
type ChildProps = {
items: Item[];
toggleState: (e: React.MouseEvent, title: string) => void;
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^
}
const Child: React.FC<ChildProps> = (props) => {
return (
{props.items.map((item) => (
<button onClick={(e) => props.toggleState(e, item.title)}> pass clicked item title to parent </button>
))}
)
// −−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^
}
Обратите внимание на изменения toggleState
в Parent.tsx
и onClick
в Child.tsx
.
Live Пример:
const { useState } = React;
/*
interface Item {
title: string;
}
*/
const items = [
{title: "Item 1"},
{title: "Item 2"},
{title: "Item 3"},
{title: "Item 4"},
];
const Parent = () => {
const [someState, setSomeState] = useState("");
const toggleState = (e/*: React.MouseEvent*/, title/*: string*/) => {
setSomeState(title);
}
return (
<div>
<div>someState = {someState}</div>
<Child items={items} toggleState={(e, title) => toggleState(e, title)} />
</div>
)
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−−−−−−−−^^^^^
}
/*
type ChildProps = {
items: Item[];
toggleState: (e: React.MouseEvent, title: string) => void;
}
*/
const Child/*: React.FC<ChildProps>*/ = (props) => {
return <React.Fragment>
{props.items.map((item) => (
<button onClick={(e) => props.toggleState(e, item.title)}> pass clicked item title to parent </button>
))}
</React.Fragment>
// −−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^
}
ReactDOM.render(<Parent />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
На игровой площадке для показа типов работ.