2016-12-26 76 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