我在浏览 React 文档时遇到了静态方法。我想知道在什么样的情况下它可能有用并且想不出任何。
在 React 中构建组件时,是否存在静态方法有用的特定场景?
最佳答案
defaultProps
和 propTypes
是 React 组件的静态成员,它们不会因每个实例而改变。参见 https://facebook.github.io/react/docs/reusable-components.html
静态属性的一个示例是能够跟踪创建了多少对象实例(不是特定于 React 的)。请注意,大多数时候,如果您正在修改状态,静态方法是一种代码味道。
var Contacts = React.createClass({
statics: {
instanceCount: 0
},
getInitialState: function() {
Contacts.instanceCount++
return {};
},
render: function() {
return (<div > Hello {
this.props.name
} < /div>);
}
});
console.log(Contacts.instanceCount) // 0
ReactDOM.render( < Hello name = "World" / > ,
document.getElementById('container')
);
console.log(Contacts.instanceCount) // 1
另一个例子是一种存储常量的方法。
var Contacts = React.createClass({
statics: {
MAX_VALUE:100
},
render: function() {
return (<div > Hello {
this.props.name
} < /div>);
}
});
if (someValue > Contacts.MAX_VALUE) {
}
关于javascript - React 中的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333996/