我读了几篇文章,建议不要在JSX属性中使用箭头函数,比如onClick、onMouseMove等。
https:/reactjs.orgdocsfaq-functions.html#is-it-ok-to-use-arrow-functions-in-render-methods。
但当涉及到JSX中箭头函数的使用对性能的影响。下面的方法在渲染x & y & z时有什么不同吗?
例子:https:/codesandbox.iosdifferent-ways-to-create-react-components-sm517。
const x = [1, 2, 3, 4, 5];
const y = [6, 7, 8, 9, 10];
const z = [11, 12, 13, 14, 15];
class MyComponent2 extends React.Component {
showY = () => {
return y.map(val => {
return <p>{val}</p>;
});
};
render() {
const zValues = z.map(val => {
return <p>{val}</p>;
});
return (
<div>
<div>
<p>React Component Using a Class</p>
{x.map(val => {
return <p>{val}</p>;
})}
</div>
<div>{this.showY()}</div>
<div>{zValues}</div>
</div>
);
}
}
使用箭头函数还是简单函数没有区别。所有关于这两种函数声明方式的规则都是来自javascript的实际和有效的。所以,使用一种函数或另一种函数是你的权利。