【问题标题】:e.target.value is undefined while adding dynamic input data in react在反应中添加动态输入数据时,e.target.value 未定义
【发布时间】:2017-01-26 01:07:38
【问题描述】:

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

// 状态

      this.state = {
        newText: {}
      };

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

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

// 渲染动态输入文本的代码。

      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未定义?

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

【问题讨论】:

  • 你能把你的代码上传到 JSFiddle.net 吗?这样可以更轻松地帮助您调试问题。
  • @KennyMeyer 我已经提供了完整代码的链接
  • @johndoe,我将您的代码修改为:jsfiddle.net/mrlew/gk55wLx1。但是changeInput没有错误。检查控制台。
  • @johndoe 改编版本,在输入处具有持久值:jsfiddle.net/mrlew/gk55wLx1/4

标签: reactjs react-native


【解决方案1】:

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

改为使用

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

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

【讨论】:

    【解决方案2】:

    你必须像&lt;Input placeholder='Type your text here' value={this.state.newText[key]} onChange={this.changeInput.bind(this)}/&gt;一样使用bind

    【讨论】:

    • 绑定后仍然不确定。
    • 如果它无论如何都没有处于绑定状态,它会抛出一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2020-05-31
    • 2021-04-28
    • 1970-01-01
    • 2022-07-22
    • 2021-06-02
    相关资源
    最近更新 更多