2015-11-22 28 views
5

我在facebook上找到了示例代碼React Native頁面,其中顯示瞭如何使用setNativeProp清除點擊文本,但我看不到如何使用多個文本框。這裏是代碼:React原生清除文本多個TextInput框

var App = React.createClass({ 
    clearText() { 
    this._textInput.setNativeProps({text: ''}); 
    }, 

    render() { 
    return (
     <View style={styles.container}> 
     <TextInput ref={component => this._textInput = component} 
       style={styles.textInput} /> 
     <TouchableOpacity onPress={this.clearText}> 
      <Text>Clear text</Text> 
     </TouchableOpacity> 
     </View> 
    ); 
    } 
}); 

參考似乎是固定的功能,所以將始終針對相同的TextInput框。我如何修改函數來定位我指出的任何TextInput框?

回答

8

這應該有效。請注意,TextInput上的ref需要是您從clearText functino中調用的那個。

var App = React.createClass({ 
    clearText(fieldName) { 
    this.refs[fieldName].setNativeProps({text: ''}); 
    }, 

    render() { 
    return (
     <View style={styles.container}> 
     <TextInput ref={'textInput1'} style={styles.textInput} /> 
     <TouchableOpacity onPress={() => this.clearText('textInput1')}> 
      <Text>Clear text</Text> 
     </TouchableOpacity> 
     <TextInput ref={'textInput2'} style={styles.textInput} /> 
     <TouchableOpacity onPress={() => this.clearText('textInput2')}> 
      <Text>Clear text</Text> 
     </TouchableOpacity> 
     </View> 
    ); 
    } 
}); 

更新了我的答案,以清除不同的字段。

+0

但你的onPress沒有值?你如何區分它與另一個onPress以清除不同的文本輸入?您仍然需要創建兩個獨立的功能。你能舉兩個textinputs和兩個touchableopacity按鈕來演示它如何使用這個函數嗎? – Hasen

+0

相應地更新了我的答案。 – eyal83

+0

好吧看起來像沿着正確的線條,但實際上並沒有工作。它在你的最後工作嗎? – Hasen

1

你也可以使用這樣的東西來清除TextInput的文本。

clearText(fieldName) { 
    this.refs[fieldName].clear(0); 
},