简体   繁体   中英

Accessing this.state value to other Class [React Native]

I just wanna ask how can i access this.state.sampleString from other class.. Here's my code

class MainClass extends Component {

  constructor(props){
      super(props)


      this.state = {
        sampleString: 'Test String'
      }

      this.getValue = this.getValue.bind(this);
    }


    getValue(){
        //console.log(this.state.sampleString);
        return this.state.sampleString
    }

}

=========

This is my function from My second class to get the value of "this.state. sampleString" from MainClass

function getValueFromMainClass() {

  var stringFromClassHeader = () => {HeaderWithBg.getValue()}

  console.log(stringFromClassHeader.sampleString);

}

Why it returns "undefined"?

Thanks alot. Im a new in react native.

You can send the this.state.sampleString as a prop to other components and use it there. A simple example of this is like below:

class MainClass extends Component {
  constructor(props){
      super(props)
      this.state = {
        sampleString: 'Test String'
      }

      this.getValue = this.getValue.bind(this);
    }

    getValue(){
        //console.log(this.state.sampleString);
        return this.state.sampleString
    }

    render(){
        return (
        <ChildClass sampleString={this.state.sampleString}/>


          )
        }
    }

class ChildClass extends Component {
    somefunction() {
        //console.log(this.props.sampleString);
        return this.props.sampleString
    }

    render(){
        return ...
    }
}

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