react 判断实例类型

今天在写组件的时候想经过判断内部子元素不一样而在父元素上应用不一样的class,因而首先要解决的就是如何判断子元素的类型。javascript

这里附上一个讲的很全面的文章:css

http://www.javashuo.com/article/p-vdehluvk-bc.htmlhtml

typeof运算符

首先说一下typeof,它是一个操做符,其右侧跟一个一元表达式,并返回这个表达式的数据类型。返回的结果用该类型的字符串(全小写字母)形式表示,包括如下 7 种:number、boolean、symbol、string、object、undefined、function 等。基本数据类型是能够判断的,可是对象就只能到object,没法区分具体的function name或者说是class name。java

if(typeof 'hello' == 'string'){
  console.log("true")
}

instanceof运算符

原文地址:https://www.cnblogs.com/SourceKing/p/5766210.htmlreact

instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另一个要检测对象的原型链上es6

instanceof的普通的用法,obj instanceof Object 检测Object.prototype是否存在于参数obj的原型链上。函数

Person的原型在p的原型链中学习

function Person(){};
var p =new Person();
console.log(p instanceof Person);//true

总结:用一个方法模拟instanceof的判断逻辑ui

function _instanceof(A, B) {
    var O = B.prototype;// 取B的显示原型
    A = A.__proto__;// 取A的隐式原型
    while (true) {
        //Object.prototype.__proto__ === null
        if (A === null)
            return false;
        if (O === A)// 这里重点:当 O 严格等于 A 时,返回 true
            return true;
        A = A.__proto__;
    }
}

通过debug,发现react的一个组件并不能经过这种方式判断。具体放到继承那边去讲吧。this

React.Children.map+elementType 

经过学习其余组件的代码,看到有这样写的

React.Children.map(this.props.children, element => {
            if (!element) {
              return null;
            }

            const { elementType } = element.type;
            if (elementType !== 'YourClass' ) {
              return null;
            }
            ...
          })

须要在本身的类里面添加一个常量(捂脸)

static elementType = 'YourClass';

 

this.props.children.type.name

最后我用的是这种方式

this.props.children&&!Array.isArray(this.props.children)&&this.props.children.type.name == 'YourClass'

若是须要在props属性列表中限制类型,能够看这个文档:

http://www.css88.com/react/docs/typechecking-with-proptypes.html

------------------------------

2018.6.26 补充

今天build了一下,上面那个方法type.name拿不到正确的值了.....尴尬......用回第三种方法。

因而决定仍是好好研究一下原理吧。。。(捂脸)

原理嘛, 一个是es6 里static 关键字,还有一个重点,敲黑板,Flowtype ,官网文档在这里

https://flow.org/en/docs/react/

相关文章
相关标签/搜索