javascript - 如何使用 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、如何TextareaItem
使用 React Hooks 获取值?我将在获取这些值后发送 ajax 请求。有一个自定义钩子react-use-form-state,但它作用于 html 表单,如何做同样的事情在 Antd Form 上?
2、如何修改 this.autoFocusInst.focus();
函数组件中的句子?
解决方案
为了使用 ref,你可以使用 useRef 钩子。componentDidMount
也可以通过提供第二个参数作为空数组来使 useEffect 表现得像。使用受控的 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;
如果您不使其成为受控输入,则可能您可以使用 ref 获取值。
推荐阅读
- html - 如何在reactjs中正确绝对定位
- powershell - Powershell Change Watcher 仅在目录上触发
- javascript - 在 React 中切换事件单击(打开/关闭)
- java - GridPane 中只有一个响应列
- ios - Swift.DecodingError.Context(编码路径:
- python - Ansible 正则表达式过滤器
- r - 在 R 中使用时间和地理坐标进行模糊连接
- c# - 如何处理来自同一个异常对象的不同类型的异常?
- python - 手动绘制 matplotlib 图例框
- python - 如何替换字符串中的单个斜杠“/”,不包括“://”模式中的斜杠字符