2017-07-30 135 views
2

我是目前正在學習的React Native,我正在嘗試創建一個可以清除多個文本輸入的清除按鈕。我用下面的鏈接,儘量使清除按鈕: https://snack.expo.io/B1xM4CjIb如何在React Native中創建一個清除按鈕

我成立這樣的例子:

export default class Input extends Component { 

    handleLocation = (text) => { 
     this.setState({ location: text }) 
} 

    handleStartTime = (text) => { 
     this.setState({ startTime: text }) 
} 

    handleEndTime = (text) => { 
     this.setState({ endTime: text}) 
} 
    login = (location, startTime, endTime) => { 
     alert('Location: ' + location + 'Start Time:' + startTime + 'End Time:' + endTime) 
} 
    clearInput =() => { 
     this.textInputRef.clear(); 
} 

render(){ 

    return (
    <View style={styles.container}> 
     <TouchableOpacity 
      style = {styles.submitButton} 
      onPress = {() => this.login(this.state.location, this.state.startTime, this.state.endTime)}> 
      <Text style = {styles.submitButtonText}> 
       Submit 
      </Text> 
     </TouchableOpacity> 
     <Button title= "Clear" onPress={this.clearInput.bind(this)}/> 
     <TextInput 
      ref={ref => this.textInputRef = ref}/> 
      value={this.state.location, this.state.startTime, this.state.endTime}/> 
    </View> 

當我運行此我得到的錯誤RawText 'Value=' must be wrapped in an explicit <Text> Component。這隻會使字詞值出現在屏幕上,而清除按鈕仍然不起作用。我該如何解決它?感謝任何能夠幫助的人。

+0

TextInput的兩個主要屬性:'OnTextChanged'和'value'。 '在TextChanged'上隨時調用用戶添加或刪除角色的功能。 'value'是任何時候寫在'TextInput'裏面的東西。據說,準備好''ref's到你的'TextInput's(其中每個都有'value = {YourValue}'<<這樣。現在點擊一下,將所有'ref.value'設置爲一個空字符串 –

+0

你能用完整的代碼再次詳細闡述您的問題? – muhammadaa

+0

你想解決'RawText「值=」必須明確'這個錯誤被包裹?或者你的代碼是不工作的清楚嗎? –

回答

0

你可以只說

clearInput =() => { 
    this.setState({ location: '', startTime: '', endTime: '' }); 
} 

而且,因爲該功能是一個箭頭的功能。在<Button>中,我們可以說onPress={this.clearInput},而不需要bind(this)

+0

然後我應該刪除這個 this.textInputRef = REF} /> 值= {this.state.location,this.state.startTime,this.state.endTime} /> –

+0

呀裁判將沒有目的。此外,溜溜你需要3'',第一個用'value = {this.state.location}',第二個用'value = {this.state.startTime}'&finally'value = {this.state.endTime}'。 – MattyK14

0

添加ref={'whatever'}到您的TextInput組件(加一個你要清理的每個文本輸入)

喜歡這個

<TextInput ref={'one'}/> 
<TextInput ref={'two'}/> 
<TextInput ref={'three'}/> 
... 

然後使用這個功能來清除文本:

clearText() { 
    this.refs.one.setNativeProps({text: ''}); 
    this.refs.two.setNativeProps({text: ''}); 
    this.refs.three.setNativeProps({text: ''}); 
} 

將其附加到按鈕上PressPress:

<TouchableOpacity onPress={(text) => this.clearText({text: ''})}/> 
相關問題