我知道有时需要设置displayName,尤其是在处理生产版本时.我想知道如何使用我的功能组件设置它 – 它是否可能/允许?
这是我在我的课程组件中得到的:
var MyComponent = React.createClass({ displayName: 'HeyHey',render: function() { console.log(this.displayName); } });
如何在无状态组件中执行相同的操作?
解决方法
displayName
的文档说
The
displayName
string is used in debugging messages. Usually,you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component,see 07001.
在您的情况下,您只需使用
const MyComponent = (props) => { ... } MyComponent.displayName = 'HeyHey'
如果您要在组件上设置默认属性,请改用defaultProps
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>