英文:
Implementing events in a REACT function component
问题
我正在尝试弄清楚如何实现我的自定义事件。我在这里提出了问题,但是"event"这个词似乎让我的问题变得混淆了。有人建议我添加一个新的问题,所以我会尽量以另一种方式来解释:
我的组件:
import React, { useState } from "react";
const DropdownPaging2 = props => {
function myClickFunc(val) {
alert("我应该在这里添加什么来触发我的事件给消费组件");
}
return <div onClick={() => myClickFunc(100)}>点击我</div>;
};
export default DropdownPaging2;
在另一个组件(消费组件)的渲染函数中使用我的组件:
<DropdownPaging2></DropdownPaging2>
我想要实现的是,我可以将一个新的事件传递给消费组件。类似这样:
<DropdownPaging2 myCustomEvent={() => myCustomEvent(100)}></DropdownPaging2>
英文:
I am trying to figure out how to implement my own custom events. I asked the question here but the word event seems to confuse my question. I was asked to add a new question, so I will try to do my best in another way:
My component:
import React, { useState } from "react";
const DropdownPaging2 = props => {
function myClickFunc(val) {
alert("WHAT SHOULD I ADD HERE TO FIRE MY EVENT TO THE CONSUMING COMPONENT");
}
return <div onClick={() => myClickFunc(100)}>CLICK me</div>;
};
export default DropdownPaging2;
Using my component in another components (comsuming component) render function:
<DropdownPaging2></DropdownPaging2>
I would like implement so I can pass a new event to the consuming component. Something lige this:
<DropdownPaging2 myCustomEvent={() => myCustomEvent(100)}></DropdownPaging2>
答案1
得分: 0
只需在组件中使用custom回调(如果它作为prop传递),否则使用default回调。
return <div onClick={prop.myCustomEvent ? prop.myCustomEvent : () => myClickFunc(100)}>点击我</div>;
英文:
Just make your component use the custom callback if it was passed as a prob, otherwise use the default one.
return <div onClick={prop.myCustomEvent ? prop.myCustomEvent : () => myClickFunc(100)}>CLICK me</div>;
答案2
得分: 0
你可以像你提到的那样将函数作为属性传递给你的DropdownPaging2组件:
<DropdownPaging2 myEvent={() => myCustomEvent(100)}></DropdownPaging2>
然后在组件中像这样使用它。
import React, { useState } from "react";
const DropdownPaging2 = props => {
const myClickFunc = (val) => {
if(props.myEvent){
props.myEvent();
} else {
// 如果未传递函数,则使用默认值
}
}
return <div onClick={() => myClickFunc(100)}>点击我</div>;
};
export default DropdownPaging2;
英文:
You can pass functions as props to your DropdownPaging2 component like you mentioned:
<DropdownPaging2 myEvent={() => myCustomEvent(100)}></DropdownPaging2>
And then use it in the component like this.
const DropdownPaging2 = props => {
const myClickFunc = (val) => {
if(props.myEvent){
props.myEvent();
} else {
// default if no function is passed
}
}
return <div onClick={() => myClickFunc(100)}>CLICK me</div>;
};
export default DropdownPaging2;
This way you are free to pass a custom function
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论