为什么在 React JS 中允许有多个“渲染”方法,后者会覆盖前者?
class Test extends React.Component { render() { return(<span>First label</span>); } render(){ return( <span>Second label</span>);} }
上面的代码呈现“Second Label”并编译正常。这是故意的还是 React JS 中的错误?
最佳答案
类基本上是函数之上的语法糖:
class foo {}
console.log(typeof foo);
类中的方法作为函数对象原型(prototype)的属性存在(这个函数对象实际上是类。更多关于原型(prototype) here)。
例如:
class foo{
bar () {console.log('random function')}
}
console.dir(foo.prototype.bar)
当您声明第二个具有相同名称的方法时,您是在一个对象(即 foo.prototype 对象)上声明一个具有相同名称的属性。较新的声明属性(即方法)将简单地覆盖现有属性(即旧方法)。
关于javascript - 为什么 React JS 允许多个 "render"方法,后者覆盖了前者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53342466/