2017-09-13 96 views
0

我的組件是:傳遞價值的TextInput onPress

class TextInputComp extends Component { 
    constructor(props){ 
    super(); 
    this.state = { thetext: '' } 
    } 

    submitText = (text) => { 
    Alert.alert("Text Submitted!", text); 
    } 

    render() { 
    const renData = this.props.people((data, index) => { 
     return (
     <View key={index} style={styles.card}> 
      <Text style={styles.names}> ID: {data.id} - Name: {data.name} </Text> 
      <TouchableOpacity 
       onPress={()=>this.refs.MyBox.focus()} > 
       <Text>Open</Text> 
      </TouchableOpacity> 
     </View> 
      ) 
     }); 
return (
     <View style={mystyles1.container}> 
     {renData} 
     <View> 
     <TextInput 
      ref='MyBox' 
      style={{height: 40}} 
      onChangeText={(thetext) => this.setState({thetext})} 
     /> 
      <TouchableOpacity 
      onPress = {() => this.submitText(this.state.thetext) }> 
       <Text style = {styles.ButtonText}> Submit </Text> 
      </TouchableOpacity> 
     </View> 
     </View> 
    ); 
    } 
} 

我可以顯示在TextInput{redData}focus數據上Open點擊時。我想將一個值傳遞給TextInput。假設我想通過data.name,所以當OpenonPress時,我想data.name已經在TextInput的開頭,所以我可以將它傳遞給this.state.thetext

我該如何做到這一點?非常感謝。

回答

2

您可以讓您的TextInput受控。對於您可以重點通過value道具TextInput這樣

<TextInput 
    ref='MyBox' 
    style={{height: 40}} 
    value={this.state.thetext} 
    onChangeText={(thetext) => this.setState({thetext})} 
    /> 

現在,所有你需要做的就是用你想在TextInput這樣

<TouchableOpacity 
    onPress={()=>{this.refs.MyBox.focus(); this.setState({thetext: data.name})}} > 
    <Text>Open</Text> 
</TouchableOpacity> 
+0

顯示該值設置thetext狀態謝謝。我確實在'TextInput'中獲得了值,但它不允許我在其中添加任何東西。它只有傳遞的價值。我嘗試輸入更多,它不讓我。爲什麼是這樣? – Somename

+0

噢..沒關係..我很抱歉。有一個錯字。它的工作現在。非常感謝你。 – Somename