如何使用React Hooks获得Antd Form的值



下面是antd mobile的TextareaItem示例,
我想用React Hooks重写它,
这是我的半成品代码:

import React, { useState, useEffect} from "react"
import { List, TextareaItem } from 'antd-mobile';
import { createForm } from 'rc-form';

function TextareaItemExample {
useEffect(() => {
//this.autoFocusInst.focus();
});
return (
<div>
<List renderHeader={() => 'Customize to focus'}>
<TextareaItem
title="title"
placeholder="auto focus in Alipay client"
data-seed="logId"
ref={el => this.autoFocusInst = el}
autoHeight
/>
<TextareaItem
title="content"
placeholder="click the button below to focus"
data-seed="logId"
autoHeight
/>
</List>
</div>
);
}
const TextareaItemExampleWrapper = createForm()(TextareaItemExample);
export default TextareaItemExampleWrapper;

问题:
1、如何使用React Hooks获得TextareaItem的值?我将在获得这些值后发送ajax请求。有一个自定义的钩子反应使用表单状态,但它作用于html表单,如何在Antd表单上做同样的事情?

2、 如何修改函数组件中的句子this.autoFocusInst.focus();

为了使用ref,可以使用useRef钩子。另外,通过提供第二个参数作为空数组,可以使useEffect的行为类似于componentDidMount。使用受控制的TextAreaItem,您也可以获得状态中的值。

import React, { useState, useEffect, useRef} from "react"
import { List, TextareaItem } from 'antd-mobile';
import { createForm } from 'rc-form';

function TextareaItemExample {
const [title, setTitle] = useState();
const [content, setContent] = useState();
const handleTitleChange = (value) => {
setTitle(value);
}
const handleContentChange = (value) => {
setContent(value)
}
const autoFocusInt = useRef();
useEffect(() => {
autoFocusInst.current.focus();
}, []);
return (
<div>
<List renderHeader={() => 'Customize to focus'}>
<TextareaItem
title="title"
value={title}
onChange={handleTitleChange}
placeholder="auto focus in Alipay client"
data-seed="logId"
ref={autoFocusInst}
autoHeight
/>
<TextareaItem
title="content"
value={content}
onChange={handleContentChange}
placeholder="click the button below to focus"
data-seed="logId"
autoHeight
/>
</List>
</div>
);
}
const TextareaItemExampleWrapper = createForm()(TextareaItemExample);
export default TextareaItemExampleWrapper;

如果你不把它作为一个受控输入,你可能会使用参考来获得值

最新更新