我正在尝试使用Formik表单创建自定义颜色选择器
她的问题是父组件的颜色未更改:
import {SketchPicker} from "react-color";
export const MyColorPicker = ({label, ...props}) => {
// with useField is should not use onChange but i get an error without defining it myself
const [field] = useField(props);
const [color, setColor] = useState("#333");
const handleChange = color => {
setColor(color.hex);
field.onChange(color.hex);
};
const onComplete = color => {
setColor(color.hex);
field.onChange(color.hex);
};
return (
<div style={{padding: 10}}>
<label>{label}</label>
<SketchPicker {...props} {...field} color={color} onChange={handleChange} onChangeComplete={onComplete} />
</div>
);
};
例如,这项工作:
export const MyTextAreaField = ({label, ...props}) => {
const [field, meta] = useField(props);
if (field && field.value === null) {
field.value = "";
}
return (
<div style={{display: "flex", flexDirection: "column"}}>
<label className="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-animated MuiInputLabel-shrink MuiFormLabel-filled">
{label}
</label>
<TextareaAutosize
rows={10}
{...field}
{...props}
style={{marginTop: 10, fontFamily: "Helvetica Neue", fontSize: 15}}
/>
{meta.touched && meta.error ? <div className="error">{meta.error}</div> : null}
</div>
);
};
和父代码:
<Formik
initialValues={{
data: { title :'', shortDescription:'', description:'', color:'')
}}
onSubmit={values => {
console.log(values.data) ; // data.color stay null
}}>
<Form>
<MyTextAreaField id="data.description" name="data.description" label={t("PROJECT.DESCRIPTION")} />
<MyColorPicker id="data.color" label={t("PROJET.COLOR")} name="data.color" />
</Form>
</Formik>
答案 0 :(得分:0)
最后我结束了这样的事情:
在父组件中:
uploadFile
组件定义
<MyColorPicker
label={t("PROJECT.COLOR")}
onChange={color => {
data.project.color = color;
}}
/>