2017-10-05 81 views
-1

我想從文本輸入提交值,但是當我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

Th是應該肯定是工作的嘗試清理你的代碼,這樣

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({ ... })

+0

我寫了這樣的this.props.submit(「410c8d94985511e7b308b870f44877c8」,「」,「e18e4e557de511e7b664b870f44877c8」),因爲我一定要考成功與否發送到服務器 –

+0

的數據,是的,仍然不確定。 –

+0

當你測試你的輸入是否顯示出來時,你可以對此進行評論,我製作了一個我發佈的代碼的副本,並且它可以正常工作,你是否可以發佈包含該代碼的整個頁面,因爲問題是來自其他地方 – linasmnew