
直接上代码~~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
export default class extends Component { render() { return( <div> <Child alias={this.doSth} /><br/> <button onClick={this.click} >父组件click</button> </div> ) }
doSth = (ref) => { this.anything = ref }
click = (e) => { this.anything.myName() }
}
class Child extends Component { componentDidMount(){ this.props.alias(this) }
myName = () => alert('click me ')
render() { return ('我是子组件') } }
|
简化下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
export default class extends Component { render() { return( <div> <Child alias={(ref)=>{this.anything = ref}}/><br/> <button onClick={()=>{this.anything.myName()}} >父组件click</button> </div> ) } }
class Child extends Component { componentDidMount(){ this.props.alias(this) }
myName = () => alert('click me ')
render() { return ('我是子组件') } }
|
上面点击按钮,会弹出子组件的输出
原文:
https://blog.csdn.net/hesonggg/article/details/79373565
近期评论