我知道有时需要设置displayName
,特别是在您处理生产版本时。我想知道如何使用我的功能组件设置它 - 是否可以/允许?
这是我在课程内容中得到的内容:
var MyComponent = React.createClass({
displayName: 'HeyHey',
render: function() {
console.log(this.displayName);
}
});

如何在无状态组件中执行相同的操作?
答案 0 :(得分:20)
想出来
const MyComponent = props => {
return (
<p>How you doin?</p>
)
}
MyComponent.displayName = "MyComponent"
&#13;
答案 1 :(得分:18)
AVG
function的文档说
displayName
字符串用于调试消息。通常,您不需要显式设置它,因为它是从定义组件的函数或类的名称推断出来的。如果要为调试目的显示不同的名称或创建更高阶的组件,可能需要显式设置它,请参阅displayName
。
在您的情况下,您只需使用
const MyComponent = (props) => { ... }
MyComponent.displayName = 'HeyHey'
如果您要在组件上设置默认属性,请改用Wrap the Display Name for Easy Debugging for details
const MyComponent = props => {
return (
<p>How you doin, {props.name}?</p>
)
}
MyComponent.defaultProps = {
name: 'Alice'
}
ReactDOM.render (<MyComponent/>, document.body)
// <p>How you doin, Alice?</p>
答案 2 :(得分:4)
将功能组件定义为箭头功能时,它们需要displayName
或功能本身的名称。
因此对于箭头功能:
const SomeComponent = () => <p>I come from an arrow function</p>
SomeComponent.displayName = 'HeyHey'
如果您使用一个函数,它将使用其名称为displayName
,而不必单独定义它:
function HeyHey() { return <p>I come from a non-arrow function!</p> }