组件的值如何反应原生

时间:2017-07-18 16:35:48

标签: javascript react-native components

我想在我的Form.js中获取电子邮件和passowrd的值,以便点击单击按钮可以将它们传递给客户端api 1.这是我的类src / components / login / Form.js

        import React, { Component } from 'react';  
        import {
            KeyboardAvoidingView,
            StyleSheet,
            TouchableHighlight,
            Image,        
        } from 'react-native';
        import UserInput from "./UserInput";       
        import usernameImg from '../../images/Iconperson.png';
        import passwordImg from '../../images/Iconlock.png';
        import eyeImg  from '../../images/eye.png';       
            export default class Form extends Component {    
              constructor(props) {
            super(props);
            this.state = {
                    email: "",
                    password: "",
                };
        }  
        _onPress() {
           console.warn("email", this.state.email)
           console.warn("password", this.state.password)
      }  
          render() {
              return (
                  <KeyboardAvoidingView behavior='padding'
                    style={styles.container}>
                    <UserInput source={usernameImg}
                   onChangeText = {(email) => this.setState({email})}
                        keyboardType = 'email-address'
                        placeholder='Username'
                        autoCapitalize={'none'}
                        returnKeyType={'done'}
                        autoCorrect={false} />
                    <UserInput source={passwordImg}
                 onChangeText = {(password) => this.setState({password})}
                        placeholder='Password'
                        returnKeyType={'done'}
                        autoCapitalize={'none'}
                        autoCorrect={false} />
                    <TouchableHighlight
                        onPress={this._onPress}
                        activeOpacity={1} >
                        <Text>LOGIN</Text>
                    </TouchableHighlight>
                </KeyboardAvoidingView>

              );
          }
      }   
      const styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: 'center',
        }
    });

2。这是我的类src / components / login / UserInput.js

    import React, { Component , PropTypes} from 'react';
    import Dimensions from 'Dimensions';
    import {
    StyleSheet,
    View,
    TextInput,
    Image,
    } from 'react-native';  
    const DEVICE_WIDTH = Dimensions.get('window').width;
    const DEVICE_HEIGHT = Dimensions.get('window').height;

    export default class UserInput extends Component {
      render() {
          return (
              <View style={styles.inputWrapper}>
                <Image source={this.props.source}
                    style={styles.inlineImg} />
                <TextInput style={styles.input}
                    onChangeText = {(this.props.ChangeText) => 
                    this.setState({field})}
                    placeholder={this.props.placeholder}
                    secureTextEntry={this.props.secureTextEntry}
                    autoCorrect={this.props.autoCorrect}
                    autoCapitalize={this.props.autoCapitalize}
                    returnKeyType={this.props.returnKeyType}
                    placeholderTextColor='white'
                    keyboardType ={this.props.keyboardType}
                    underlineColorAndroid='transparent' />
            </View>

          );
      }
    }

    UserInput.propTypes = {
    ChangeText : PropTypes.string,
    source: PropTypes.number.isRequired,
    placeholder: PropTypes.string.isRequired,
    keyboardType : PropTypes.string,
    secureTextEntry: PropTypes.bool,
    autoCorrect: PropTypes.bool,
    autoCapitalize: PropTypes.string,
    returnKeyType: PropTypes.string,
    };
    const styles = StyleSheet.create({
    input: {
        backgroundColor: 'rgba(255, 255, 255, 0.2)',
        width: DEVICE_WIDTH - 40,
        height: 40,
        marginHorizontal: 20,
        paddingLeft: 45,
        borderRadius: 20,
        color: '#ffffff',
    },
    inputWrapper: {
        flex: 1,
    },
    inlineImg: {
        position: 'absolute',
        zIndex: 99,
        width: 22,
        height: 22,
        left: 35,
        top: 9,
    },
    });

2 个答案:

答案 0 :(得分:2)

当您在TextInput中输入时,我看到您正在尝试更改Form组件中的状态。为了正确地发生这种情况,需要从Form组件调用setState。目前有几个函数通过道具传递:

(email) => this.setState({email})
// and
(password) => this.setState({password})

查看 UserInput 组件中如何使用这些内容,每当向该文本框添加新字符时,请调用上述函数。因此,当调用this.setState()时,它会说UserInput.setState()。由于我们想要改变 Form 中的状态,我们必须将这些函数绑定到父组件。

不要将函数直接传递给props,而是添加一些用户方法:

export default class Form extends Component {
  constructor(props) {}

  _onChangeEmail(email) {
    this.setState(Object.assign({}, state, { email })); // good practice for immutability
  }

  _onChangePassword(password) {
    this.setState(Object.assign({}, state, { password })); // good practice for immutability
  }

  render() {}
}

接下来,我们需要将这些类方法绑定到自身。这样无论在何处调用它们,都将始终指向Form组件。这通常在构造函数中完成:

export default class Form extends Component {
  constructor(props) {
    super(props)
    this.state = {}

    // this is where we do the binding
    this._onChangeEmail = this._onChangeEmail.bind(this)
    this._onChangePassword = this._onChangePassword.bind(this)
  }

  _onChangeEmail(email) { /* code */}

  _onChangePassword(password) { /* code */}

  render() {}
}

现在通过props将这些传递给UserInput组件:

// Form.js
render() {
  return (
    <KeyboardAvoidingView>
      <UserInput onChangeText={this._onChangeEmail} />
      <UserInput onChangeText={this._onChangePassword} />
    </KeyboardAvoidingView>
  )
}

现在,当用户输入文字时,应使用这些方法:

export default class UserInput extends Component {
  render() {
    return (
      <View>
        <Image  />
          <TextInput onChangeText = {this.props.onChangeText} />
      </View>
    );
  }
}

奖金:你还应该添加一个属性&#39;值&#39;到文本输入:

export default class UserInput extends Component {
  render() {
    return (
      <View>
        <Image  />
          <TextInput
            onChangeText={this.props.onChangeText} />
            value={this.props.textValue} 
      </View>
    );
  }
}

并确保它从父组件传递下来:

// Form.js
render() {
  return (
    <KeyboardAvoidingView>
      <UserInput
        onChangeText={this._onChangeEmail}
        textValue={this.state.email}/>
      <UserInput
        onChangeText={this._onChangePassword}
        textValue={this.state.password}/>
    </KeyboardAvoidingView>
  )
}

答案 1 :(得分:0)

TextInput的值可以通过其_lastNativeTextproperty检索。

this.refs.myTextInput._lastNativeText

请参见this answer