未定义的TextInput值

时间:2017-10-05 09:16:26

标签: javascript react-native react-native-android

我想从文本输入中提交值,但是当我在console.log中时,之前输入的文本是未定义的。我已经按照react native get TextInput value的说明进行操作,但仍未定义。

这是我之前做过的状态:

this.state = {
  comment_value: '',
  comments: props.comments
}

submit = (args) => {
  this.props.submit(args.comment_value)
}

这是提交文本的功能:

addComment () {

var comment_value = this.state.comment_value
console.log('success!', comment_value)
})

this.props.submit('410c8d94985511e7b308b870f44877c8', '', 'e18e4e557de511e7b664b870f44877c8')

}

这是我的textinput代码:

<TextInput
underlineColorAndroid='transparent'
placeholder='Enter your comment here'
multiline numberOfLines={4}
   onChangeText={(text) => this.setState({comment_value: text})}
                value={this.state.comment_value}
                style={styles.textinput}

      />
            </View>
            <TouchableOpacity onPress={this.addComment.bind(this)}>
              <View style={{flex: 1, flexDirection: 'column', backgroundColor: Colors.background, width: 70}}>
                <Icon name='direction' type='entypo' color='#000'size={30} style={styles.icon} />
              </View>
            </TouchableOpacity>

1 个答案:

答案 0 :(得分:1)

这应该是有效的尝试清理你的代码

contructor(props) {
   super(props);
   this.state = {
      comment_value: '',
   }
}

addComment () {
  console.log(this.state.comment_value); // should be defined
  this.props.submit(this.state.comment_value);
}

render() {
    return (
      <View>
          <TextInput
             underlineColorAndroid='transparent'
             placeholder='Enter your comment here'
             multiline numberOfLines={4}
             value={this.state.comment_value}
             onChangeText={(text) => this.setState({comment_value: text})}
             style={styles.textinput}
          />

          <TouchableOpacity onPress={this.addComment.bind(this)}>
              <View style={{flex: 1, flexDirection: 'column', backgroundColor: Colors.background, width: 70}}>
                  <Icon name='direction' type='entypo' color='#000'size={30} style={styles.icon} />
              </View>
          </TouchableOpacity>
      </View>
    );
}

编辑:根据您的完整代码示例,您似乎错误地尝试通过执行多个this.state = ...来更新状态,这是不正确的,更新状态您必须使用this.setState({ ... })

相关问题