首页 > 解决方案 > Formik 自定义颜色选择器

问题描述

我正在尝试使用 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>
  );
};

标签: javascriptreactjsformik

解决方案


最后我结束了这样的事情:

在父组件中:

<MyColorPicker
     label={t("PROJECT.COLOR")}
     onChange={color => {
         data.project.color = color;
     }}
  />

组件定义

export const MyColorPicker = ({label, onChange}) => {   
  const [color, setColor] = useState("#333");      
  const handleChange = color => {
    setColor(color.hex);
  };
  return (
    <div
      style={{display: "flex", flexDirection: "row", justifyContent: "flex-start", alignItems: "center", padding: 10}}>
      <label>{label}</label>
      <ChromePicker color={color} onChange={handleChange} onChangeComplete={color=> onChange(color.hex) } />
    </div>
    )     
})

推荐阅读