【问题标题】:Pass value to TextInput onPress将值传递给 TextInput onPress
【发布时间】:2017-09-13 20:20:44
【问题描述】:

我的组件是:

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>
    );
  }
}

当点击Open 时,我可以在TextInput 上显示来自{redData}focus 的数据。我想将一个值传递给TextInput。假设我想传递data.name,所以当onPress 位于Open 上时,我希望data.name 已经在TextInput 的开头,这样我就可以将它传递给this.state.thetext

我怎样才能做到这一点?非常感谢。

【问题讨论】:

    标签: reactjs react-native ecmascript-6 react-native-text


    【解决方案1】:

    您可以控制您的TextInput。为此,您可以像这样将value 属性传递给TextInput

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

    现在重点是,您所要做的就是将thetext 状态设置为您希望在TextInput 中显示的值,如下所示

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

    【讨论】:

    • 谢谢。我确实得到了TextInput 中的值,但它不允许我在其中添加更多内容。它只有传递的值。我试着输入更多,它不让我。这是为什么呢?
    • 哦..没关系..对不起。有一个错字。它现在工作。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2021-05-30
    相关资源
    最近更新 更多