2016-12-26 28 views
0

どのように反応ネイティブで要素を取得しますか?getElementById react-native

私のユースケースはログイン画面です。送信ボタンが押されたので、ユーザー名とパスワードのTextInputsの値を取得します。

 export default class Login extends Component 
     { 
     login() 
     { 
      //document.getElementById('username'); //run-time error 
     } 
     render() 
     { 
      return (

      <View style={{flex: 1,flexDirection: 'column',justifyContent: 'space-between',margin:10}}> 
       <View style={{backgroundColor: 'powderblue'}} /> 
       <MyTextField id='user' placeholder="User Name" /> 
       <MyTextField id='pass' placeholder="Password" /> 
       <MyButton onPress={this.login} title='Login'/> 
      </View> 

     ); 
     } 
     } 
+0

は –

答えて

4

あなたは反応ネイティブでgetElementByIdを取得していないため、状態を使用する必要があります。あなたは次のように行うことができます。

export default class Login extends Component { 

     constructor (props) { 
      super(props); 
      this.state={ 
       email:'', 
       password:'' 
      } 
      this.login = this.login.bind(this); // you need this to be able to access state from login 
     } 

     login() { 
      console.log('your email is', this.state.email); 
      console.log('your password is', this.state.password); 
     } 

     render() { 
      return (
      <View style={{flex: 1,flexDirection: 'column',justifyContent: 'space-between',margin:10}}> 
       <View style={{backgroundColor: 'powderblue'}} /> 
       <TextInput onChangeText={(email) => { 
      this.setState({email})/> 
       <TextInput secureTextEntry={true} onChangeText={(password) => { 
      this.setState({password})/> 
       <MyButton onPress={this.login} title='Login'/> 
      </View> 
     ); 
     } 
     } 
+0

感謝をhttps://facebook.github.io/react/docs/forms.html読みます。その値はカスタムコンポーネントの代わりに親に保持されているという私には奇妙なものです。リアクションのように、「カプセル化」は望ましくないので、オブジェクト指向ではありません。その場合、 'Prop'として、私はLoginと 'name'を渡す必要があると思うので、私のカスタムTextInputではsetState({name:テキスト})? – user1709076

+0

ありがとうございます。あなたは学びの悩みの中で私を助けることができました – user1709076

+0

はい、あなたは親に設定して子に渡すことができます – Codesingh