reactjs - Passing an event up from a child element to a great-grandfather -
i'm getting familiar react native. using setup this, i'm able pass child parent:
child:
<touchableopacity onpress={() => {this.props.click("cool.")}}>
parent:
constructor(props) { super(props); this.click = this.click.bind(this) } click(c) { console.log(c) // "cool." } render() { return ( <view> <child click={this.click}> </view> } }
however, if change parent's return to:
<view> <child click={this.props.click}> </view>
then use grandfather component:
<view> <parent click={this.click}> </view>
i'm not getting click event, error "_this2.props.click not function"
changing child element <touchableopacity onpress={this.props.click}>
seems prevent event being handled.
ultimately, i'd have child element trigger event handler @ great-grandfather level modify state @ root level , cascade changes downward.
you can access child's methods using ref
. can see document of in here. simple example of using ref
below:
class child extends component { open = () => { this.props.setvisible(true) } render () { <view ref={this.props.reffunc}> ... </view> } } class parent extends component { _ref = (e) => { this._child = e } runfunction = () => { this._child.open(); // can use open function of child here } render () { ... <child reffunc={this._ref}> ... } }
and when want modify parent child should define function , pass child component prop
, use on event onpress
in child component. achieve sample code this:
class parent extends component { state = {somestate: value} changestatevalue = (val) => { this.setstate({somestate: val}) } render () { ... <child changestate={this.changestatevalue}> ... } } class child extends component { changeparentstate = (val) => () => { this.props.changestate(val) } render () { ... <touchablehighlight onpress={this.changeparentstate(value)}> ... </touchablehighlight> ... } }
in way can access parent state child component.
Comments
Post a Comment