Formik пользовательский палитра цветов - PullRequest
0 голосов
/ 23 марта 2020

Я пытаюсь создать пользовательскую палитру цветов с формой 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>   
    

1 Ответ

0 голосов
/ 24 марта 2020

наконец я закончил делать что-то вроде этого:

В родительском компоненте:

<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>
    )     
})
...