javascript - 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>
);
};
和父代码:
<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>
解决方案
最后我结束了这样的事情:
在父组件中:
<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>
)
})
推荐阅读
- ios - 如何在 socket.io 中使用数据?迅速
- python - 你如何在 ANN 中实现神经元?
- c++ - 如何从复数返回实数
- android - 如何从附近的手机获取 BLE 信号?
- python - 硒滚动到页面顶部
- bison - 野牛中的“其余线路”
- ios - 如果 supportsOnDeviceRecognition 为 true 并且离线模式可用,SFSpeechRecognizer 是否有限制?
- excel - 使用 Dictionary 方法匹配两个工作表中的数据 17,500 行需要 15 分钟
- python - 如何获得熊猫数据框中列表中每个元素的频率分布?
- javascript - clearTimeout 内有多个超时