本文介绍了在反应中添加动态输入数据时 e.target.value 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次点击按钮时需要添加一个输入框(input-0, input-1...).以下是相关代码.

I need to add an input box (input-0, input-1...) each time a button is clicked.Following is the relevant code.

//状态

      this.state = {
        newText: {}
      };

//添加动态输入文本的代码

// Code to add dynamic input text

      addInputText = () => {
        let dynamicTextsNo = Object.keys(this.state.newText).length;
        let newInputId = dynamicTextsNo+1;
        let dynamicTextArr = this.state.newText;
        let newTextId = 'input-'+dynamicTextsNo;
        dynamicTextArr[newTextId] = '';
        let newState = { ...this.state, newText: dynamicTextArr }
        this.setState( newState );
      }

//呈现动态输入文本的代码.

// Code to render dynamic input text.

      dynamicTextArea = () => {
        return Object.keys(this.state.newText).map( ( key ) => {
          return  ( <InputGroup key={key} borderType='underline'>
                      <Input placeholder='Type your text here' value={this.state.newText[key]} onChange={this.changeInput}/>
                    </InputGroup>
                  );
        });
      }

//渲染函数

      render() {
        return <View>{this.dynamicTextArea()}</View>
      }

//处理输入

  changeInput = (e) => {
    console.log( e.target.value ); // **this comes out to be undefined.**
  }

为什么 changeInput 函数中的 e.target.value 未定义?

Why is e.target.value in changeInput function undefined?

附言完整代码的jsfiddle链接:https://jsfiddle.net/johnnash03/9by9qyct/1/

P.S. Jsfiddle link of the full code: https://jsfiddle.net/johnnash03/9by9qyct/1/

推荐答案

与浏览器文本输入元素不同,event 参数传递给 React Native TextInput.onChange 回调没有名为 target 的属性.

Unlike with the browser text input element, the event argument passed to React Native TextInput.onChange callback does not have a property called target.

改为使用

<TextInput
  onChange={(event) => event.nativeEvent.text}
/>

<TextInput
  onChangeText={(text) => text}
/>

这篇关于在反应中添加动态输入数据时 e.target.value 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!