【问题标题】:Accessing this.state value to other Class [React Native]将 this.state 值访问到其他类 [React Native]
【发布时间】:2018-02-19 05:57:30
【问题描述】:

我只是想问一下如何从其他类访问 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 的新手。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您可以将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 ...
        }
    }
    

    【讨论】:

    • 你能给我一个示例代码吗?我是新来的本地人。非常感谢先生!
    • 谢谢先生!! :)
    • 很高兴为您提供帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2018-07-11
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多