好久没写博客了,以前一直写vue,18年最后一个季度又开始经常写react,这次写一个基于antd form组件的自定义Input组件,写一个最简单的,让刚接触antd的小伙伴们能快速的了解基于form组件的自定义Input组件该如何入手。
import React, { PureComponent } from 'react';
import { Input, Icon } from 'antd';
class InputClear extends PureComponent {
constructor(props) {
super(props);
this.state = {
isShow: false,
v: '',
timer: null
};
}
componentDidMount() {
this.setState({
v: this.props.value || ''
});
}
UNSAFE_componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
this.setState({
v: nextProps.value
});
}
}
componentWillUnmount() {
clearTimeout(this.state.timer);
this.setState({
timer: null
});
}
handleFocus = (e) => {
let value = e.target.value;
this.setState({ isShow: !!value });
}
handleChange = (e) => {
const { onChange } = this.props;
if (onChange) onChange(e.target.value);
this.handleFocus(e);
}
clearInput = () => {
const { isNeedClear, onChange } = this.props;
if (isNeedClear && onChange) {
onChange('');
}
this.setState({
isShow: false
});
}
handleBlur = () => {
this.state.timer = setTimeout(() => {
this.setState({
isShow: false
});
}, 200);
}
render() {
const { isShow, v } = this.state;
return (
suffix={isShow ? : null}
autoComplete="off"
placeholder="请输入"
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onChange={this.handleChange}
value={v}
/>
);
}
}
export default InputClear;
这是一个在输入框里动态添加取消输入框里面的内容的组件,有几个要素,第一就是onchange事件需要回调给form,第二个就是componentWillReceiveProps里需要把输入值传给组件,componentDidMount是用来回显初始值的,还有一点是组件不能使函数式组件。
如果大家有更好的想法欢迎和我一起讨论哦,技术不分国界不分年龄,一起探讨,一起进步~