2016-12-26 74 views
0

如何獲取react-native中的元素?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

閱讀https://facebook.github.io/react/docs/forms.html –

回答

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

謝謝。它對我來說很奇怪,值是保存在父代而不是自定義組件 - 就像React不想'封裝' - 所以它不是面向對象的?如果是這樣的話,那麼作爲一個'道具',我想我需要傳遞Login和'name',這樣在我自定義的TextInput中,我可以用setState({name:文字})? – user1709076

+0

非常感謝。你幫助我學習了一個駝峯 – user1709076

+0

是的,你是對的,你可以在父母身上設置狀態並傳給孩子 – Codesingh