<Parent>
<Child config = {toggle: funciton(){console.log(this)}}></Child>
</Parent>
在子组件里this.props.config.toggle()
,这时在父组件里的this并不指向父组件本身,假如改成this.props.config.toggle.bind(this)()
,这时的this指向子组件。那应该怎么让这个this指向父组件呢。
方法一:可以考虑把父组件的this传给子组件,bind的时候用传递的这个值;
方法二:使用箭头函数
class Parent extends React.Component {
toggle = () => {
console.log(this)
}
render() {
return <Child config = {toggle: this.toggle}></Child>
}
}
子组件使用this.props.config.toggle()
调用。
在父组件里绑定函数的this
。
class Parent extends React.Component {
toggle = () => {
console.log(this)
}
render() {
return <Child config = {toggle: this.toggle}></Child>
}
}
###你可以使用继承
, 子组件继承一个父组件, 此时子组件中就有父组件的属性和方法了