我在这篇文章中读到React is Slow, React is Fast: Optimizing React Apps in Practice:
实际上,每次将对象文字作为prop传递给子组件时,都会破坏纯度。
好吧,我明白了。因此,最好避免这种情况是使用对象创建变量,并在prop中插入此变量,如下所示:
import React from 'react';
const style = { marginTop: 10 };
const AnyComponent = (props) => (
<div style={style}>
...
</div>
)
但是如果风格支柱取决于收到的道具呢?对象应该在哪里?例如,我有这个组件:
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>
)
}
}