admin管理员组文章数量:1289383
I'm using react & typescript.
I wonder how i can pass event from parent to child with props.
so is example
parent.tsx
const ParentComponent: React.FC<ParentProps> = (props) => {
const [activeItem, setActiveItem] = useState("");
const getActiveItem = (e: React.MouseEvent, title: string) => {
setActiveItem(title)
};
return (
<ChildComponent activeItem={activeItem} clickHandler={(e) => getActiveItem(e, 'TITLE')} />
)
}
child.tsx
interface ChildProps {
activeItem: string;
clickHandler: () => any;
}
const ChildComponent: React.FC<ChildProps> = (props) => {
return (
<button onClick={props.clickHandler} /> {props.activeItem} </button>
)
}
and on parent ponent i'm getting error on clickHandler:
Type '(e: any) => void' is not assignable to type '() => void'.ts(2322)
I'm using react & typescript.
I wonder how i can pass event from parent to child with props.
so is example
parent.tsx
const ParentComponent: React.FC<ParentProps> = (props) => {
const [activeItem, setActiveItem] = useState("");
const getActiveItem = (e: React.MouseEvent, title: string) => {
setActiveItem(title)
};
return (
<ChildComponent activeItem={activeItem} clickHandler={(e) => getActiveItem(e, 'TITLE')} />
)
}
child.tsx
interface ChildProps {
activeItem: string;
clickHandler: () => any;
}
const ChildComponent: React.FC<ChildProps> = (props) => {
return (
<button onClick={props.clickHandler} /> {props.activeItem} </button>
)
}
and on parent ponent i'm getting error on clickHandler:
Type '(e: any) => void' is not assignable to type '() => void'.ts(2322)
Share
Improve this question
asked Apr 28, 2020 at 13:55
ciz30ciz30
4533 gold badges12 silver badges19 bronze badges
2 Answers
Reset to default 8This is how the typings for the click handler should be:
interface ChildProps {
activeItem: string;
clickHandler: (e: React.MouseEvent<HTMLButtonElement>) => void;
}
You should not use any
as the type for the parameter, as on click event handler accepts Event
as the parameter.
In your child prop you give type click handler clickHandler: () => any;
, it does not expect any params.
But when you give the function in the parent ponent, you give e
as a parameter. So they don't match.
You could type your clickHanler : clickHandler: (e: any) => any;
But you should probably avoid any
, and try : (e: React.MouseEvent) => any
.
本文标签: javascriptReact amp Typescript how get onClick prop from child to parentStack Overflow
版权声明:本文标题:javascript - React & Typescript how get onClick prop from child to parent - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741449140a2379382.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论