在react中添加动态输入数据时e.target.value未定义

joh*_*doe 0 reactjs react-native

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

//状态

      this.state = {
        newText: {}
      };
Run Code Online (Sandbox Code Playgroud)

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

      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 );
      }
Run Code Online (Sandbox Code Playgroud)

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

      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>
                  );
        });
      }
Run Code Online (Sandbox Code Playgroud)

//渲染功能

      render() {
        return <View>{this.dynamicTextArea()}</View>
      }
Run Code Online (Sandbox Code Playgroud)

//处理输入

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

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

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

jev*_*lio 7

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

相反,使用

<TextInput
  onChange={(event) => event.nativeEvent.text}
/>
Run Code Online (Sandbox Code Playgroud)

要么

<TextInput
  onChangeText={(text) => text}
/>
Run Code Online (Sandbox Code Playgroud)