javascript - Accessing this.state value to other Class [React Native] - Stack Overflow

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

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.

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.

Share Improve this question edited Mar 16, 2019 at 20:08 Vahid Boreiri 3,4481 gold badge20 silver badges35 bronze badges asked Sep 11, 2017 at 4:20 nico aurelio villanuevanico aurelio villanueva 1152 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You can send the this.state.sampleString as a prop to other ponents 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 ...
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744969319a4603871.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信