如何检索React Native中按钮Click onPress上的文本输入输入值?

时间:2019-04-14 08:21:22

标签: react-native

我是React Native的新手,我无法一一检索在textInput上输入的内容。

示例:如果我输入了一些名称,它应该一个一个地出现...

  state = {
    name: "",
    showName: false
  };

  buttonClickListner = e => {
    const { showName } = this.state;

    this.setState({ showName: true });
  };

  render() {
    const { name } = this.state;
    return (
        <TextInput
          style={{ height: 150 }}
          placeholder="Enter a Name...."
          value={name}
          onChangeText={val => {
            this.setState({
              name: val
            });
          }}
        />
        <Button
          onPress={this.buttonClickListner}
          title="Submit"
          color="#008000"
        />
        <Text>{(showName = true ? name : null)}</Text>    
  );
  }
}

2 个答案:

答案 0 :(得分:1)

以下是一些要点:

  • 首先,您应该从返回中返回单个根或具有片段的多个元素(读取片段here)。因此,将它们全部包装在单个标签中,例如//您的组件等。

  • 您正在分配showName = true而不是进行检查。使用 showName === true 吗?语法。

还有完整的代码和runnig sample

import * as React from 'react';
import { Button, TextInput, Text, View} from 'react-native';

export default class App extends React.Component{
  state = {
      name: "",
      showName: false
    };

  buttonClickListner = e => {
    const { showName } = this.state;
    this.setState({ showName: true });
  };

  render() {
    const { name, showName } = this.state;
    return (
        <View>
          <TextInput
            style={{ height: 150 }}
            placeholder="Enter a Name...."
            value={name}
            onChangeText={val => {
              this.setState({
                name: val
              });
            }}
          />
          <Button
            onPress={this.buttonClickListner}
            title="Submit"
            color="#008000"
          />
          <Text>{(showName === true ? name : null)}</Text>   
        </View> 
      );
  }
}

答案 1 :(得分:-1)

我已经完成了您所需要的。无论在该TextInput中键入什么内容,都需要一个名称序列,但是使用字符串不可能需要一个数组来显示要输入的所有值。

export default class App extends React.Component {
   state = {
    name: [],
    showName: false,
    text:""
  };

  buttonClickListner = e => {
    this.state.name.push( this.state.text.toString() );
    this.setState({text:""})
  };
  render() {
    const { name } = this.state;
    return (
      <View>
        <TextInput
          style={{ height: 150 }}
          placeholder="Enter a Name...."
          value={this.state.text}
          onChangeText={val => {
            this.setState({
              text: val
            });
          }}
        />
        <Button
          onPress={this.buttonClickListner}
          title="Submit"
          color="#008000"
        />
        {this.state.name.length>0?this.state.name.map(item=>(<Text>{item}</Text>)):null} 
        </View>
  );
}
}
相关问题