javascript – 如何在功能组件中设置displayName [React]

前端之家收集整理的这篇文章主要介绍了javascript – 如何在功能组件中设置displayName [React]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道有时需要设置displayName,尤其是在处理生产版本时.我想知道如何使用我的功能组件设置它 – 它是否可能/允许?

这是我在我的课程组件中得到的:

var MyComponent = React.createClass({
    displayName: 'HeyHey',render: function() {
        console.log(this.displayName);
    }
});

如何在无状态组件中执行相同的操作?

解决方法

displayName的文档说

The displayNamestring 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>
原文链接:https://www.f2er.com/js/156035.html

猜你在找的JavaScript相关文章