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

时间:2017-09-11 04:20:35

标签: javascript reactjs react-native

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

INSERT INTO data(id, map) VALUES('123-123-12321', {'object2' : {value : '2', timestamp : '2017-09-09 16:24:06.197000+0000'}}) USING TIMESTAMP 1504952646912000;

======

这是我的第二课的功能,以获得" this.state的值。 sampleString"来自MainClass

<html>

<body>
  <h3>Land Lubber's Pirate Translator</h3>
  <p>Simply click on the buttons to translate words and/or phrases from English to pirate talk.
  </p>
  <form action="#">
    <input type="button" value="hello" onclick="document.getElementById('outputDiv').innerHTML=
 document.getElementById('outputDiv').innerHTML + 'ahoy ';">
    <input type="button" value="stranger" onclick="document.getElementById('outputDiv').innerHTML =
 document.getElementById('outputDiv').innerHTML + 'scurvy dog ';">
    <input type="button" value="Clear the Translation" onclick="document.getElementById('outputDiv').innerHTML = '';">
  </form>
  <hr>
  <div id="outputDiv"></div>
</body>

</html>

为什么它会返回&#34; undefined&#34;?

非常感谢。我是一个反应原生的新人。

1 个答案:

答案 0 :(得分:2)

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