React受控组件在Firefox中不会自动完成

时间:2016-12-12 23:03:59

标签: firefox reactjs

在React中使用受控输入时,自动完成功能在Firefox中不起作用,但在Chrome中不起作用。因此,它与表单元素上的属性autocomplete off无关,因为我没有使用它。

这是我用来呈现受控输入元素的代码:

<input style={inputStyle} id={this.props.id} type={this.props.type} placeholder={this.props.placeholder} value={this.props.value} onChange={this.props.onChange} />

这是从父组件(对于电子邮件字段)传递到此组件的onChange函数:

_updateEmail(event) {
    this.setState({email: event.target.value.substr(0, 100)});
}

这里有两个截图,显示它在Firefox中不起作用,但在Chrome中起作用。

铬:

火狐:

如果我将受控输入转换为普通输入,则可以使用Firefox。所以这真的很奇怪。

1 个答案:

答案 0 :(得分:0)

这是React中已知的issue。解决问题的最佳方法是禁用自动填充,或使用auto-fill polyfil。

或者,您可以在ReactJS之外处理此案例并直接使用DOM,如问题中所述:

export default class Input extends Component {
  static propTypes = {
    value: PropTypes.string,
    onFieldChange: PropTypes.func,
  };

  static defaultProps = {
    value: '',
  }

  componentDidMount() {
    this._listener = setInterval(() => {
      if (!this.input || this._previousValue === this.input.value) {
        return;
      }

      this._previousValue = this.input.value;

      const evt = document.createEvent('HTMLEvents');
      evt.initEvent('input', true, true);
      this.input.dispatchEvent(evt);
    }, 20);
  }

  componentWillUnmount() {
    clearInterval(this._listener);
  }

  refInput = (input) => this.input = input;

  render() {
    const { label,
      value,
      onFieldChange,
    } = this.props;

    this.input = this.input || { value };

    return (
        <input
            value={this.input.value}
            onChange={onFieldChange}
            ref={this.refInput}
        />
    );
  }
}