reactjs - 是否可以将 simple-react-code-editor 作为 Formik 字段组件?
问题描述
试图让这个表单字段组件采用简单的反应代码编辑器:
不确定我是否通过尝试从useField
钩子中传递道具来以正确的方式解决这个问题,但它适用于文本字段标签,所以认为同样的方法也适用于此。虽然,我觉得回调与该组件没有的onValueChange
回调不同。onChange
有没有办法以某种方式添加它?
编辑器组件:
const MyEditor = ({value, onChange}) => {
const highlight = (value) => {
return(
<Highlight {...defaultProps} theme={theme} code={value} language="sql">
{({ tokens, getLineProps, getTokenProps }) => (
<>
{tokens.map((line, i) => (
<div {...getLineProps({ line, key: i })}>
{line.map((token, key) => (
<span {...getTokenProps({ token, key })} />
))}
</div>
))}
</>
)}
</Highlight>
)
};
return (
<Editor
value={value}
onValueChange={onChange}
highlight={highlight}
padding={'40px'}
style={styles.root}
/>
);
}
export default MyEditor;
使用字段组件作为 MyEditor 的表单(尝试使用 useField 挂钩):
const FormQueryTextBox = ({...props}) => {
const [field] = useField(props);
return (
<MyEditor onChange={field.onChange} value={field.value}/>
)
}
const validationSchema = yup.object({
query_name: yup
.string()
.required()
.max(50)
});
const AddQueryForm = () => {
return (
<div>
<Formik
validateOnChange={true}
initialValues={{
query:""
}}
validationSchema={validationSchema}
onSubmit={(data, { setSubmitting }) => {
console.log(data);
}}
>
{() => (
<Form>
<div>
<Field
placeholder="query name"
name="query_name"
type="input"
as={TextField}
/>
</div>
<div>
<Field
name="query"
type="input"
as={FormQueryTextBox}
/>
</div>
</Form>
)}
</Formik>
</div>
)
}
组件呈现没有错误,但是当我键入文本时没有出现。
解决方案
我发现我只需要使用 useFormikContext 钩子中的设置器来自定义我的 onChange ,如下所示:
const FormQueryTextBox = ({...props}) => {
const [field] = useField(props);
const { setFieldValue } = useFormikContext();
return (
<MyEditor {...field} {...props} onChange={val => {
setFieldValue(field.name, val)
}}/>
)
}
推荐阅读
- c - net/core/filter.c 和 linux/bpf/verifier.c
- javascript - JavaScript 执行时间线
- laravel - 如何根据时间戳获取最新记录,但不能从 laravel 中的表中复制?
- opencv - 如何将图像作为python代码中使用的c++函数的输出返回>
- unity3d - 在 Unity 中为对象绘制纹理
- rest - baseUrl 和 callbackUrl 的区别
- haskell - 为什么我们需要 WalletApi 的 startWatching 函数?
- excel - 增加 Excel 中单元格范围的现有值@每 100 个
- go - 是否可以捕获此零指针错误
- scala - 配置 Akka Alpakka kafka 以调查挂起的消费者