简体   繁体   中英

access child component state in parent component in react-native

I have a Searchbar component within react-native that is imported within a parent component,

The SearchBar child component has the following element:

         <Search
            ref={component => this._search = component}
            onChangeText={this.searchUpdated} 
            blurOnSubmit
            useClearButton={false}
            backgroundColor='#15A5E3'
          />
         searchUpdated(term) {
          return new Promise((resolve, reject) => {
          this.setState({ searchTerm: term });
          resolve();
         });
        }

Is is possible to access the state of this child component within the parent in which it is imported? Thanks in advance fo the help

You can set the 'ref' prop of any react component, and then inside the Parent component you can access any methods from the child like this:

this.refs.child.childMethod()

An example:

Child Component

class ChildComponent extends Component {

   getState() {
    return this.state
   }

   render() {
    return <Text>I'm a child</Text>
   }
}

Parent Component:

class ParentComponent extends Component {

   manipulateChildState() {
    let child = this.refs.childRef.getState()
    // do something here
   }

   render() {
    return <Child ref='childRef' />
   }
}

Just remember to use the same String on this.refs.REFERENCE and on the prop ref='REFERENCE'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM