【问题标题】:How to get values from dynamically created textInput in React Native?如何从 React Native 中动态创建的 textInput 获取值?
【发布时间】:2020-10-14 16:35:27
【问题描述】:

我从用户选择中得到一个计数 - 例如,当用户选择 5 意味着我将得到

const count = 5;

通过保持这一点,我可以使用 for 循环动态创建 textInput,并且它可以完美运行!但是如何在用户键入时将值存储在状态中?我无法理解如何执行此操作!我已经尝试过了,但它给出了错误提示值不应该包含数组作为输入,

 state = { userDetails: [] }

textHandler(texts){
        this.setState({...this.state.userDetails, texts})
    }

for (let i = 0; i < count; i++) {
            items.push(
    <TextInput 
           style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
           placeholder="Enter Name"
           onChangeText={text => this.textHandler(text)}
           value={this.state.userDetails}
   /> ) }

【问题讨论】:

  • 您基于count创建了5个输入字段?
  • 您想将所有值存储在数组或任何值类型的输入中?
  • 是的@TasosBu
  • 由于 textInput 的计数在 1 到 6 之间变化,我认为数组将有助于对 @NooruddinLakhani 进行分组
  • 如何显示输入?你使用 .map() 方法吗?

标签: javascript reactjs react-native


【解决方案1】:

这可能会有所帮助(已更新)

class App extends Component {
  
  componentDidMount() {
    this.getDynamicInputs();
  }

  state = { userDetails: [], item_views: [] };

  updateState = (index, value) => {
    const userDetails = [...this.state.userDetails]; //make a copy of array
    userDetails[index] = value;
    this.setState({ userDetails: userDetails });
  };

  getDynamicInputs() {
    const inputData = [];
    for (let i = 0; i < count; i++) {
      inputData.push(
        <TextInput
          key={i}
          style={{ borderBottomWidth: 1, borderColor: "#f0eff4", height: 40 }}
          placeholder="Enter Name"
          onChangeText={(val) => this.updateState(i, val)}
          value={this.state.userDetails[i]}
        />
      );
    }
    this.setState({ item_views: inputData });
  }

  render() {
    console.log(this.state.userDetails);
    return <View style={styles.app}>{this.state.item_views}</View>;
  }
}

const styles = StyleSheet.create({
  app: {
    flex: 1,
    backgroundColor: "pink"
  }
});

export default App;

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 2020-11-15
    • 2019-03-01
    • 2016-03-28
    • 2020-10-24
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多