React可以将原型分配给子组件,而不是传递槽道具? 我们可以做这样的事情:我们可以给儿童组件分配原型吗?
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>
)
}
}
我不是很肯定,如果我做错了什么,但代码的作品?
您有几种选择在这里 - 家长可以通过两种道具传递函数来从子组件调用。或者,如果您有几个组件可能会或可能不是父级的孩子,但仍然需要该功能 - 您可以创建更高级别的组件(HOC)。 简而言之,HOC需要一个组件并返回一个添加了功能的新组件。 https://egghead.io/lessons/react-react-fundamentals-higher-order-components-replaces-mixins https://facebook.github.io/react/docs/higher-order-components.html –