访问 this.state 值到其他类 [React Native] [英] Accessing this.state value to other Class [React Native]

查看:43
本文介绍了访问 this.state 值到其他类 [React Native]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想问我如何从其他类访问 this.state.sampleString .. 这是我的代码

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
    }

}

==========

这是我的第二个类的函数,用于从 MainClass 获取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"?

非常感谢.我是 React Native 的新手.

Thanks alot. Im a new in react native.

推荐答案

您可以将 this.state.sampleString 作为道具发送到其他组件并在那里使用它.一个简单的例子如下:

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 ...
    }
}

这篇关于访问 this.state 值到其他类 [React Native]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆