React无状态组件中的事件处理程序 [英] Event Handlers in React Stateless Components

查看:32
本文介绍了React无状态组件中的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出在React无状态组件中创建事件处理程序的最佳方法.我可以做这样的事情:

Trying to figure out an optimal way to create event handlers in React stateless components. I could do something like this:

const myComponent = (props) => {
    const myHandler = (e) => props.dispatch(something());
    return (
        <button onClick={myHandler}>Click Me</button>
    );
}

这里的缺点是,每次呈现此组件时,都会创建一个新的"myHandler"函数.有没有更好的方法可以在仍然可以访问组件属性的无状态组件中创建事件处理程序?

The drawback here being that every time this component is rendered, a new "myHandler" function is created. Is there a better way to create event handlers in stateless components that can still access the component properties?

推荐答案

将处理程序应用于功能组件中的元素通常应该看起来像这样:

Applying handlers to elements in function components should generally just look like this:

const f = props => <button onClick={props.onClick}></button>

如果您需要做更复杂的事情,则表明a)组件不应是无状态的(使用类或钩子),或b)您应在外部有状态容器组件中创建处理程序

If you need to do anything much more complex it's a sign that either a) the component shouldn't be stateless (use a class, or hooks), or b) you should be creating the handler in an outer stateful container component.

顺便说一句,并且稍微破坏了我的第一点,除非组件位于应用程序中特别密集的重新渲染部分,否则无需担心在 render()中创建箭头功能.

As an aside, and undermining my first point slightly, unless the component is in a particularly intensively re-rendered part of the app there's no need to worry about creating arrow functions in render().

这篇关于React无状态组件中的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆