本机获取TextInput值

时间:2015-10-02 18:14:53

标签: react-native

我遇到了一个非常简单的问题。我有登录表单,用户名,密码和按钮。在我的按钮处理程序中,我尝试获取textinput值。但总是得到不确定的价值。我错过了什么吗?

render() {
        <ExScreen
          headerColor={this.state.headerColor}
          scrollEnabled={this.state.enableScroll}
          style={styles.container} >
          <View >
            <View  >
              <View style={[styles.inputContainer]} >
                <TextInput
                  ref= "username"
                  onChangeText={(text) => this.setState({text})}
                  value={this.state.username}
                />
              </View>
 <Button style={{color: 'white', marginTop: 30, borderWidth: 1, borderColor: 'white', marginLeft: 20*vw, marginRight: 20*vw, height: 40, padding: 10}} 
             onPress={this._handlePress.bind(this)}>
              Sign In
            </Button>   
...
 _handlePress(event) {
    var username=this.refs.username.value;

16 个答案:

答案 0 :(得分:46)

快速且不太优化的方法是在onChangeText回调中使用arrow函数,方法是将username作为参数传递给onChangeText回调。

<TextInput
    ref= {(el) => { this.username = el; }}
    onChangeText={(username) => this.setState({username})}
    value={this.state.username}
/>

然后在您的_handlePress方法

_handlePress(event) {
    let username=this.state.username;
}

但这有几个缺点!!!

  1. 在此组件的每个渲染上都会创建一个新的箭头功能。
  2. 如果子组件是PureComponent,它将不必要地强制重新渲染,这会导致巨大的性能问题,尤其是在处理大型迭代的大型列表,表或组件时。 More on this in React Docs
  3. 最佳做法是使用像handleInputChange这样的处理程序,并在构造函数中绑定```this``。

    ...
    constructor(props) {
      super(props);
      this.handleInputChange = this.handleInputChange.bind(this);
    }
    
    ...
    handleInputChange(event = {}) {
      const name = event.target && event.target.name;
      const value = event.target && event.target.value;
    
      this.setState([name]: value);
    }
    ...
    
    render() {
      ...
      <TextInput
        name="username"
        onChangeText={this.handleChange}
        value={this.state.username}
      />
      ...
    }
    
    ...
    

    或者,如果您使用es6类属性速记,它会自动绑定this。但是在测试和性能方面,这有缺点。 Read More Here

    ...
    handleInputChange = (event = {}) => {
      const name = event.target && event.target.name;
      const value = event.target && event.target.value;
    
      this.setState([name]: value);
    }
    ...
    
    render() {
      ...
      <TextInput
        name="username"
        onChangeText={this.handleChange}
        value={this.state.username}
      />
      ...
    }
    
    ...
    

答案 1 :(得分:16)

在React Native 0.43中:(可能晚于0.43就可以了。)

---
version_001:
  id: 1
  item_type: 'DistributionChannel'
  item_id: 1
  event: 'create'
  whodunnit: <%= User.find_by(email: 'user@example.com').id.to_s %>
  object: nil
  created_at: 2017-05-15 12:00:00.000000000 Z
  object_changes: '---\\nid:\\n- \\n- 1\\nprimary_channel:\\n- \\n- Best Buy\\nsecondary_channel:\\n- \\n- ''\ncreated_at:\\n- \\n- 2017-05-15 12:00:00.000000000 Z\\nupdated_at:\\n- \\n- 2017-05-15 12:00:00.000000000 Z\\n'

enter image description here

答案 2 :(得分:13)

如果您像我一样,并且不想使用或污染一次性组件的状态,这就是我所做的:

export default class Registartion extends Component {
  _register = () => {
    const payload = {
      firstName: this.firstName,
      /* other values */
    }

    console.log(payload)
  }

  render() {
    return (
      <RegisterLayout>
        <Text style={styles.welcome}>
          Register
        </Text>

        <InputText
          placeholder="First Name"
          onChangeText={(text) => this.firstName = text} />
        // More components...
        <CustomButton
          backgroundColor="steelblue"
          handlePress={this._register}>
          Submit
        </CustomButton>
     </RegisterLayout>
    )
  }
}

答案 3 :(得分:8)

您应该使用状态来存储输入字段的值。 https://facebook.github.io/react-native/docs/state.html

  • 要使用setState
  • 更新州值
  

onChangeText = {(value)=&gt; this.setState({username:value})}

  • 并获得像这样的输入值
  

this.state.username

示例代码

export default class Login extends Component {

    state = {
        username: 'demo',
        password: 'demo'
    };

    <Text style={Style.label}>User Name</Text>
    <TextInput
        style={Style.input}
        placeholder="UserName"
        onChangeText={(value) => this.setState({username: value})}
        value={this.state.username}
    />

    <Text style={Style.label}>Password</Text>
    <TextInput
        style={Style.input}
        placeholder="Password"
        onChangeText={(value) => this.setState({password: value})}
        value={this.state.password}
    />

    <Button
        title="LOGIN"
        onPress={() => 
            {
                if(this.state.username.localeCompare('demo')!=0){
                    ToastAndroid.show('Invalid UserName',ToastAndroid.SHORT);
                    return;
                }

                if(this.state.password.localeCompare('demo')!=0){
                    ToastAndroid.show('Invalid Password',ToastAndroid.SHORT);
                    return;
                }

                //Handle LOGIN

            }
        }
    />

答案 4 :(得分:4)

请注意如何使用setState()。正确的形式是

this.setState({
      Key: Value,
    });

所以我会这样做:

onChangeText={(event) => this.setState({username:event.nativeEvent.text})}
...    
var username=this.state.username;

答案 5 :(得分:2)

export default class App extends Component {
  state = { username: '', password: '' }

  onChangeText = (key, val) => {
    this.setState({ [key]: val})
  }
  
  render() { 
    return (
      <View style={styles.container}>
          <Text>Login Form</Text>
          <TextInput
            placeholder='Username'
            onChangeText={val => this.onChangeText('username', val)}
            style={styles.input}
          />
          <TextInput
            placeholder='Password'
            onChangeText={val => this.onChangeText('password', val)}
            style={styles.input}
            secureTextEntry={true}
          />      
      </View>
    );
  }
}

希望这可以解决您的问题

答案 6 :(得分:2)

只需这样做。

this.state={f_name:""};

textChangeHandler = async (key, val) => {
    await this.setState({ [key]: val });
}

<Textfield onChangeText={val => this.textChangeHandler('f_name', val)}>

答案 7 :(得分:1)

这对我有用

    <Form>

    <TextInput
    style={{height: 40}}
    placeholder="userName"
    onChangeText={(text) => this.userName = text}
    />

    <TextInput
    style={{height: 40}}
    placeholder="Password"
    onChangeText={(text) => this.Password = text}
    />


    <Button 
    title="Sign in!" 
    onPress={this._signInAsync} 
    />

    </Form>

  _signInAsync = async () => {
        console.log(this.userName)
        console.log(this.Password) 
  };

答案 8 :(得分:1)

尝试控制台记录对象,您将在nativeEvent.text中找到输入的文本

示例:

handelOnChange = (enteredText) => {
    console.log(enteredText.nativeEvent.text)
}
render()
return (
    <SafeAreaView>
        <TextInput
            onChange={this.handelOnChange}
        >
</SafeAreaView>

)

答案 9 :(得分:0)

班级初级用户:

constructor() {
    super()
    this.state = {
        email: ''
    }
}

然后在某个功能中:

handleSome = () => { console.log(this.state.email) };

在输入中:

<TextInput onChangeText={(email) => this.setState({email})}/>

答案 10 :(得分:0)

如果设置文本状态,为什么不直接使用它?

_handlePress(event) {
  var username=this.state.text;

当然,变量命名可能比“文本”更具描述性,但是你的调用。

答案 11 :(得分:0)

通过此过程,一切对我都可以:

<Input onChangeText={this.inputOnChangeText} />

还有:

inputOnChangeText = (e) => {
  this.setState({
    username: e
  })
}

答案 12 :(得分:0)

constructor(props) {
        super(props);

        this.state ={
            commentMsg: ''         
        }
    }

 onPress = () => {
          alert("Hi " +this.state.commentMsg)
      }

 <View style={styles.sendCommentContainer}>

     <TextInput
        style={styles.textInput}
        multiline={true}
        onChangeText={(text) => this.setState({commentMsg: text})}
        placeholder ='Comment'/>

       <Button onPress={this.onPress} 
           title="OK!"
           color="#841584"
        />

  </TouchableOpacity>

</View>

答案 13 :(得分:0)

onChange的{​​{1}}和onTextChange道具之间存在巨大差异。不要像我一样使用<TextInput />返回onTextChange,不要使用string返回完整对象。

花1个小时弄清楚自己的价值在哪里,我感到很愚蠢。

答案 14 :(得分:-1)

这段代码对我有用。我错过的是我没有在按钮动作中传递'this':

 onPress={this._handlePress.bind(this)}>
--------------

  _handlePress(event) {
console.log('Pressed!');

 var username = this.state.username;
 var password = this.state.password;

 console.log(username);
 console.log(password);
}

  render() {
    return (
      <View style={styles.container}>

      <TextInput
      ref="usr"
      style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10 , padding : 10 , marginLeft : 5 , marginRight : 5 }}
      placeHolder= "Enter username "
      placeholderTextColor = '#a52a2a'

      returnKeyType = {"next"}
      autoFocus = {true}
      autoCapitalize = "none"
      autoCorrect = {false}
      clearButtonMode = 'while-editing'
      onChangeText={(text) => {
          this.setState({username:text});
        }}
      onSubmitEditing={(event) => {
     this.refs.psw.focus();

      }}
      />

      <TextInput
      ref="psw"
      style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10,marginLeft : 5 , marginRight : 5}}
      placeholder= "Enter password"
      placeholderTextColor = '#a52a2a'
      autoCapitalize = "none"
      autoCorrect = {false}
      returnKeyType = {'done'}
      secureTextEntry = {true}
      clearButtonMode = 'while-editing'
      onChangeText={(text) => {
          this.setState({password:text});
        }}
      />

      <Button
        style={{borderWidth: 1, borderColor: 'blue'}}
        onPress={this._handlePress.bind(this)}>
        Login
      </Button>

      </View>
    );``
  }
}

答案 15 :(得分:-2)

你试过吗

var username=this.state.username;