简体   繁体   English

在React.js中声明无状态功能组件的首选方式是哪种?为什么?

[英]Which one is your preferred way of declaring Stateless functional components in React.js and Why ?

Function Declaration 功能声明

function MyComponent(props, context) {}

Function Expression 函数表达式

const MyComponent = function(props, context){}

Arrow function 箭头功能

const MyComponent = (props, context) => {}

Function Declaration if you want hoisting and prefer readability over performance. 函数声明,如果您要提升并且更喜欢可读性而不是性能。

Function Expression if you want to name your function so you can identify it easier from debugging stack traces (eg from Chrome dev tools). 如果要命名函数,则可以使用函数表达式,以便可以通过调试堆栈跟踪(例如,通过Chrome开发工具)更轻松地识别函数。

Arrow Function if you want if you don't care about having an anonymous function in your stack trace and want to avoid binding this . 箭头函数,如果您不想在堆栈跟踪中包含匿名函数,并且希望避免绑定this函数。

My stateless components look like this, which seems very clean to me and pretty much looks just like HTML. 我的无状态组件看起来像这样,对我来说似乎很干净,并且几乎就像HTML。 Also, es6 arrow functions assume the return expression if you dont use brackets, so you can leave those out: 此外,如果您不使用方括号,则es6箭头函数会采用return表达式,因此可以将其省略:

const Table = props => 
    <table className="table table-striped table-hover">
        <thead>
            <tr >
                <th>Name</th>
                <th>Contact</th>
                <th>Child Summary</th>
            </tr>
        </thead>
        <tbody>
            {props.items.map(item => [
                <TableRow itemId={item.id} />,
                item.isSelected && <TableRowDetails itemId={item.id} /> 
            ])}
        </tbody>
    </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM