【问题标题】:Keep getting an error "undefined is not an object (evaluating '_this.refs.name.value')"不断收到错误“未定义不是对象(评估'_this.refs.name.value')”
【发布时间】:2018-10-07 23:38:07
【问题描述】:

我正在开发 ReactNative 移动应用。 WebApp 运行顺畅,一切正常。但是当我将所有内容传输到移动部分时,我在输入字段中输入文本时遇到错误。我做错了什么,我的错误是什么?这是我的代码:

import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';

export default class App extends React.Component {

  state={
    message:"Hi {name}, your rating for this app is {rating}"
  }

    handleName=()=>{
      this.setState({
        message:"Hi "+this.refs.name.value+", your rating for this app is {rating}"
      })
    }

    handleRating=()=>{
      this.setState({
        message:"Hi "+this.refs.name.value+", your rating for this app is "+this.refs.rating.value
      })
    }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          placeholder="Your Name"
          ref="name"
          onChangeText={this.handleName}
        />
        <TextInput
          placeholder="Your Rating"
          ref="rating"
          onChangeText={this.handleRating}
        />
        <View>{this.state.message}</View>
      </View>
    );
  }
}

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

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    我不认为像这样引用TextInput 组件(使用字符串引用)是实现这一目标的最佳方式。但是,如果您愿意,可以使用this.refs.name._lastNativeText 来访问TextInput 的当前值,而不是this.refs.name.value

    在我看来,更好的方法是使用onChangeText() 回调返回的值。你可以这样做:

    import React from 'react';
    import { StyleSheet, TextInput, View } from 'react-native';
    
    export default class App extends React.Component {
    
      constructor(props) {
        super(props);
    
        this.state = {
          name: null,
          rating: null,
          message: null,
        }
      }
    
      render() {
        return (
          <View style={styles.container}>
            <TextInput
              placeholder="Your Name"
              onChangeText={text => this.setState({name: text})}
            />
            <TextInput
              placeholder="Your Rating"
              onChangeText={text => this.setState({rating: text})}
            />
            { this.state.name && this.state.rating &&
            <Text>Hi {this.state.name}, your rating for this app is {this.state.rating}.</Text>
            }
          </View>
        );
      }
    }
    

    我没有测试过这段代码,如果你遇到一些错误,请在下面评论。

    【讨论】:

    • 使用`_lastNativeText`代替state prop有什么不利影响?
    • 本身没有“不利”影响,但以下划线字符开头的变量通常仅供内部使用(即用于TextInput 类本身,而不是任何地方外面)。更多详情请咨询this answer。另一方面,State props 是为此目的而构建的,在这种情况下,它们是推荐的方式。
    猜你喜欢
    • 2018-07-22
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多