getElementById react-native

7

如何在react-native中获取元素?

我的用例是登录界面。当提交按钮被按下时,我希望获取用户名和密码的TextInput的值。

      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>

          );
        }
      }

阅读 https://facebook.github.io/react/docs/forms.html,了解有关编程的内容。 - Andy Ray
2个回答

8

在React Native中,你不需要使用getElementById方法,而是需要使用state。你可以像这样操作:

  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>
          );
        }
      }

谢谢。对我来说,奇怪的是值保存在父组件中而不是自定义组件中 - 就像React不想要“封装” - 那么它就不是面向对象的吗?如果是这样的话,那么作为一个'Prop',我认为我需要传递登录和一个'name',这样在我的自定义TextInput中,我可以使用setState({name:text})设置父级状态(即登录)? - user1709076
没错,你可以在父组件中设置状态并传递给子组件。 - Codesingh
你的回答并没有回答问题。我看到可以做到OP所问的,但还没有完全弄清楚如何做到。 - ekkis

0
在React组件中处理事件是使用绑定的最常见情况。但是现在在ES7箭头函数中,您不需要在constructor中添加此绑定: < p > 是的,我在谈论上面的绑定

this.login = this.login.bind(this);

在你的构造函数中:

constructor (props) {
      super(props);
      this.state={
          email:'',
          password:''
      }
      this.login = this.login.bind(this);
  }

想象一下,你有大约5到10个处理程序,每次创建一个方法时都要绑定它们。

使用箭头函数,您采用了封闭作用域的this绑定。您只需执行以下操作即可绑定该方法:

这里是语法:

exampleMethod = () => {
  //this is bound to the class
}

在上面的例子中,登录方法将是:
  login = () => {
      console.log('your email is', this.state.email);
      console.log('your password is', this.state.password);
  }

你还可以在组件事件处理程序的 apply/call 内联中创建简单的绑定,并通过在 render 中使用箭头函数来避免更改 this 上下文。一个例子将是

<MyButton onPress={() => this.login()} title='Login'/>

这是来自上面的例子。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接