在render()中反应函数 [英] React functions inside render()

查看:112
本文介绍了在render()中反应函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有将功能放置在react组件内的偏好。我仍在学习反应,因此只想找出最佳做法。

Is there a preference on where you put functions inside a react component. I am still learning react so just trying to figure out the best practices.

class Content extends React.Component {
    /// Whats the difference between putting functions here such as 
   Hello(){

   }

  render(){
      /// or here
   Hello(){

   }


    return()(
      <div>blah blah </div>

    )

    }


  }


推荐答案

将在每个渲染器中创建render方法中的一个函数,这对性能影响不大。如果将它们放入渲染中也很麻烦,这是一个更大的原因,您不必滚动渲染中的代码即可查看html输出。始终将它们放在类中。

A function in the render method will be created each render which is a slight performance hit. It's also messy if you put them in the render, which is a much bigger reason, you shouldn't have to scroll through code in render to see the html output. Always put them on the class instead.

对于无状态组件,最好将函数保留在main函数之外并传递props,否则将创建该函数每个渲染。我尚未测试性能,所以我不知道这是否是微优化,但值得注意。

For stateless components, it's probably best to keep functions outside of the main function and pass in props instead, otherwise the function will be created each render too. I haven't tested performance so I don't know if this is a micro-optimization but it's worth noting.

示例:

const MyStatelessComponent = ({randomProp}) => (
    render() {
        doSomething(randomProp);

        return <div />
    }
);

doSomething = (randomProp) => {
    //Do something here
}

这篇关于在render()中反应函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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