Javascript 我们可以将原型分配给子组件吗?
在React中,可以将原型分配给子组件,而不是传递槽道具吗? 我们可以这样做吗:Javascript 我们可以将原型分配给子组件吗?,javascript,reactjs,Javascript,Reactjs,在React中,可以将原型分配给子组件,而不是传递槽道具吗? 我们可以这样做吗: import React, { Component } from 'react' import Child from './Child' export default class Parent extends Component { constructor (){ super() this.parentMethod = this.parentMethod.bind(this) }
import React, { Component } from 'react'
import Child from './Child'
export default class Parent extends Component {
constructor (){
super()
this.parentMethod = this.parentMethod.bind(this)
}
parentMethod() {
// this method is going to be assigned to Child
console.log('I am invoked from child')
}
render() {
Child.prototype = this.parentMethod
// now
return <Child />
}
}
//Child.js
import React, { Component } from 'react'
export default class Child extends Component {
constructor () {
super ()
}
handleButton() {
this.parentMethod()
}
render() {
return (
<button onClick={this.handleButton.bind(this)} > click </button>
)
}
}
import React,{Component}来自“React”
从“./Child”导入子项
导出默认类父扩展组件{
构造函数(){
超级()
this.parentMethod=this.parentMethod.bind(this)
}
父方法(){
//此方法将被分配给子对象
console.log('从子级调用我')
}
render(){
Child.prototype=this.parentMethod
//现在
返回
}
}
//Child.js
从“React”导入React,{Component}
导出默认类子扩展组件{
构造函数(){
超级()
}
把手扣(){
这是parentMethod()
}
render(){
返回(
点击
)
}
}
我不太确定我是否做错了什么,但代码是否有效?首先,更改对象的
.prototype
属性不会设置其实际原型。设置对象原型的唯一可靠方法是函数。因此,您尝试的方法无法可靠地工作
但是,即使你是用正确的方式做的,你也不应该这样做:
因为ES6class
es只是原型之上的语法糖,所以不应该这样做。您的React组件依赖于组件
原型,以确保在正确的时间调用它们的生命周期方法,并且在构建对象时正确处理它们的道具。尝试更改React组件的原型只会将其搞糟,使其不再像真正的React组件那样工作
如果希望子组件能够访问其父组件的方法,正确的方法是将该方法作为道具传递
例如:
export default class Parent extends Component {
// React component constructors receive props
constructor (props){
super(props)
this.parentMethod = this.parentMethod.bind(this)
}
parentMethod() {
// this method is going to be assigned to Child
console.log('I am invoked from child')
}
render() {
return <Child parentCallback={this.parentMethod} />
}
}
//Child.js
import React, { Component } from 'react'
export default class Child extends Component {
//no constructor needed if you just call super()
render() {
return (
<button onClick={this.props.parentCallback} > click </button>
)
}
}
导出默认类父扩展组件{
//React组件构造函数接收道具
建造师(道具){
超级(道具)
this.parentMethod=this.parentMethod.bind(this)
}
父方法(){
//此方法将被分配给子对象
console.log('从子级调用我')
}
render(){
返回
}
}
//Child.js
从“React”导入React,{Component}
导出默认类子扩展组件{
//如果只调用super(),则不需要构造函数
render(){
返回(
点击
)
}
}
理论上,您可以让您的子组件
扩展父组件,但这将是一种糟糕的面向对象设计,关于原因有很多很好的论证。您可以尝试使用类似于此处的混合插件
这里有几个选项-父组件可以通过要从子组件调用的道具传递函数。或者,如果您有多个组件可能是父级的子级,也可能不是父级的子级,但仍然需要该功能,那么您可以创建一个高阶组件(HOC)。简而言之,HOC获取一个组件并返回一个具有附加功能的新组件。
var calculatorMixin = Base => class extends Base {
calc() { }
};
var randomizerMixin = Base => class extends Base {
randomize() { }
};
class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }