我在这篇文章React is Slow, React is Fast: Optimizing React Apps in Practice中读到:
实际上,每次将对象文字作为 prop 传递给子组件时,都会破坏纯度。
好吧,我明白了。所以最好避免这种情况是用对象创建一个变量,并将这个变量插入到道具中,就像这样:
import React from 'react';
const style = { marginTop: 10 };
const AnyComponent = (props) => (
<div style={style}>
...
</div>
)
但是如果 style 属性依赖于接收到的属性呢?对象应该在哪里?例如,我有这个组件:
import React from 'react';
const AnyComponent = (props) => (
<div style={{ marginTop: props.marginTop }}>
...
</div>
)
这样做是一个好习惯吗:
import React from 'react';
const style = (marginTop) => ({ marginTop })
const AnyComponent = (props) => (
<div style={style(props.marginTop)}>
...
</div>
)
[编辑] 我忘了说我的大部分组件都有状态,所以在这种情况下,这样做是个好主意:
import React from 'react';
class App extends React.Component {
style = () => ({
marginTop: this.props.marginTop
})
render() {
return(
<div style={this.style()}>
</div>
)
}
}