ive 在 react formik 中创建了一个自定义文本字段。在其他一些组件中使用文本字段并输入内容并清除所有值并单击其他地方时,仅显示第一个值(已清除的单词)。
所以文本框组件有一个输入标签
所以在这个例子中输入任何单词后,如果我输入“约翰”。
清除字段中的所有内容,现在它是空白的。
选择其他字段
该字段现在显示“J”。尽管清除了一切
class CustomInputComponent extends Component {
constructor(props) {
super(props);
this.state = {
focused: false
};
this.onFocus = this.onFocus.bind(this);
this.onBlur = this.onBlur.bind(this);
}
onFocus() {
this.setState({
focused: true
});
}
onBlur() {
this.setState({
focused: false
});
}
render() {
const {
type,
title,
field,
label,
customClass,
readOnly,
customInputStyle,
maxLength,
ariaLabel,
ariaLabelBy,
autoComplete,
htmlFor
} = this.props;
let fieldClass = `form-control form-control-danger ${styles.inputField}`;
if (customClass) {
fieldClass = `${fieldClass} ${customClass}`;
}
// console.log('field.value', field.value);
const inputContainerClass = this.state.focused || (field.value && field.value !== '') ? styles.inputFocused : styles.inputBlur;
const labelClass = this.state.focused || (field.value && field.value !== '') ? styles.labelFocused : styles.labelBlur;
return (
<div className={inputContainerClass}>
<label htmlFor={htmlFor} className={cn(labelClass, styles.customLabel)}>
{label}
</label>
<input
{...field}
type={type}
title={title}
value={field.value || ''}
className={fieldClass}
onFocus={this.onFocus}
onBlur={this.onBlur}
disabled={readOnly}
style={customInputStyle}
maxLength={maxLength}
aria-label={ariaLabel}
aria-labelledby={ariaLabelBy}
autoComplete={autoComplete}
/>
</div>
);
}
}
在 child 中重用上述组件
import {customInputComponent} from ***
const randomComponent = () => {
const getInitialValues = () => {
let values = {};
values = {
guestName: '',
}
return values;
}
const formComp = () => {
return (
<Form>
<customInputComponent guestName={guestName} />
</Form>
)
}
return (
<Formik
render={renderData => formComp(renderData)}
initialValues={getInitialValues()}
onSubmit={handleSubmit}
enableReinitialize
/>
)
}
所以在此示例中输入任何单词后,如果我键入“John”。 清除字段中的所有内容,现在它是空白的。 选择其他字段 该字段现在显示“J”。尽管清除了一切