首页 > 解决方案 > React Native,redux 形式,原生基础 - onChange(event) 函数不起作用,undefined 不是评估 event.target.value 的对象

问题描述

改变了,仍然没有答案 我遵循了这个例子: https ://jsfiddle.net/4np9u17g/11/ 我想让它像那里一样 - 输入值后焦点应该转到下一个输入。我使用 refs 和 redux 形式的新语法,我做错了什么?

  constructor() {
    super();
    this.field1 = React.createRef();
    this.field2 = React.createRef();
    this.field3 = React.createRef();
    this.field4 = React.createRef();
    this.field5 = React.createRef();
    this.field6 = React.createRef();
  }

关于更改功能(我现在让它变得非常简单):

 onChange = (text) => {
   if (text.length === 1) {
    this.field3.focus();
}

};

输入组件:

  InputComponent = ({ input, meta, ...rest }) => (
    <Input {...rest} keyboardType="numeric" maxLength={1} value={input.value} onChangeText={input.onChange} />
  );

最后是我的 redux 表单字段之一:

 <Field
    maxLength={
    id="2"
    ref={this.field1}
    style={styles.input}
    name="pinSix1"
    component={this.InputComponent}
    placeholder="*"
    onChange={this.onChange}
    secureTextEntry
  />
  <Field
    id="3"
    ref={this.field2}
    style={styles.input}
    name="pinSix2"
    component={this.InputComponent}
    placeholder="*"
    onChange={this.onChange}
    secureTextEntry
  />

我得到一个错误

undefined 不是函数(评估 '_this.field3.focus()')

标签: reactjsreact-nativereact-reduxredux-form

解决方案


好吧,经过几个小时的挣扎,这就是我必须做的(正如我所说,我正在使用新的 refs 语法,React 16.3)。我创建了 InputComponent ,其中 ref 作为道具传递:

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Input } from 'native-base';

class InputComponent extends PureComponent {
  static navigationOptions = {
    header: null,
  };

  render() {
    const { input, externalRef, ...rest } = this.props;
    return (
      <Input
        {...rest}
        ref={externalRef}
        keyboardType="numeric"
        maxLength={1}
        value={input.value}
        onChangeText={input.onChange}
      />
    );
  }
}

InputComponent.propTypes = {
  input: PropTypes.object,
  externalRef: PropTypes.object,
};

export default InputComponent;

然后在实现 pin 码输入的组件中:

constructor() {
    super();
    this.field0 = React.createRef();
    this.field1 = React.createRef();
    this.field2 = React.createRef();
    this.field3 = React.createRef();
    this.field4 = React.createRef();
    this.field5 = React.createRef();
  }

  componentDidMount() {
    this.field0.current._root.focus();
  }

  onChange = (text, val, body, name) => {
    if (text.length === 1 && name !== '6') {
      this[`field${name}`].current._root.focus();
    } else if (text.length === 1 && name === '6') {
      this.field5.current._root.blur();
    }
  };

这里的问题是这个可怕的 NativeBase 输入,它的 focus() 和 blur() 函数难以访问。最后 - 我的六个领域之一:

<Field
   externalRef={this.field0}
   style={styles.input}
   name="1"
   component={InputComponent}
   placeholder="*"
   onChange={this.onChange}
   secureTextEntry
 />

现在,当用户输入一些数字时,它会转到下一个输入,当他或她在最后一个字段中输入时,blur() 函数就会运行。


推荐阅读