Javascript 将this.state值访问到其他类[React Native]

Javascript 将this.state值访问到其他类[React Native],javascript,reactjs,react-native,Javascript,Reactjs,React Native,我只是想问一下如何从其他类访问此.state.sampleString。。这是我的密码 class MainClass extends Component { constructor(props){ super(props) this.state = { sampleString: 'Test String' } this.getValue = this.getValue.bind(this); }

我只是想问一下如何从其他类访问此.state.sampleString。。这是我的密码

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”的值

function getValueFromMainClass() {

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

  console.log(stringFromClassHeader.sampleString);

}
为什么返回“未定义”


非常感谢。我是react native中的新成员。

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

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 ...
    }
}
class MainClass扩展组件{
建造师(道具){
超级(道具)
此.state={
示例字符串:“测试字符串”
}
this.getValue=this.getValue.bind(this);
}
getValue(){
//log(this.state.sampleString);
返回此.state.sampleString
}
render(){
返回(
)
}
}
类ChildClass扩展组件{
somefunction(){
//console.log(this.props.sampleString);
返回此.props.sampleString
}
render(){
回来
}
}

您能给我一个示例代码吗?我是新来的。。非常感谢,先生!谢谢你,先生!!:)很高兴帮助你。:)