在 React 中使用受控输入时,自动完成功能在 Firefox 中不起作用,但在 Chrome 中起作用。因此,它与表单元素上的属性自动完成功能无关,因为我没有使用它。
这是我用来渲染受控输入元素的代码:
<input style={inputStyle} id={this.props.id} type={this.props.type} placeholder={this.props.placeholder} value={this.props.value} onChange={this.props.onChange} />
Run Code Online (Sandbox Code Playgroud)
这是从父组件传递到该组件的 onChange 函数(对于电子邮件字段):
_updateEmail(event) {
this.setState({email: event.target.value.substr(0, 100)});
}
Run Code Online (Sandbox Code Playgroud)
这里有 2 个屏幕截图,显示它在 Firefox 中不起作用,但在 Chrome 中可以。
铬合金:

火狐浏览器:

如果我将受控输入转换为普通输入,它确实可以在 Firefox 中使用。这就是真正奇怪的部分。
这是 React 中的一个已知问题。解决问题的最佳方法是禁用自动完成功能,或使用自动填充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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2898 次 |
| 最近记录: |