共计 864 个字符,预计需要花费 3 分钟才能阅读完成。
需要:封装 MyInput 组件,输出拼音过程不触发 onChange,拼音输入完结才触发 onChange
原理:输出拼音过程触发 composition 事件,英文 / 数字输出不触发,而 onChange 两者都触发,用一个锁管制 onChange 的机会
问题:无奈做到 MyInput 只向外裸露 onChange 事件,且使得 MyInput 受控
// MyInput.jsx
import {PureComponent} from "react";
class MyInput extends PureComponent {constructor(p) {super(p);
this.state = {input: "",};
this.lock = false;
}
handleCompositionStart = () => (this.lock = true);
handleCompositionEnd = (e) => {const { onChange} = this.props;
let input = e.target.value;
this.lock = false;
onChange(input);
this.setState({input,});
};
handleChange = (e) => {const { onChange} = this.props;
let input = e.target.value;
this.setState({input,});
if (!this.lock) {onChange(input);
}
};
render() {const { input} = this.state;
return (
<input
value={input}
onCompositionStart={this.handleCompositionStart}
onCompositionEnd={this.handleCompositionEnd}
onChange={this.handleChange}
/>
);
}
}
应用:
// App.jsx
const App = () => {return <MyInput onChange={handleChange} />;
};
正文完