如何通过React Hooks获取Antd Form的值?

时间:2018-12-12 11:26:40

标签: javascript reactjs react-hooks

以下是TextareaItem的antd-mobile示例,
我想用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请求。有一个自定义钩子react-use-form-state,但是它作用于html表单,如何执行相同的操作在Antd Form上发生了什么?

2,如何在功能组件中修改句子this.autoFocusInst.focus();

1 个答案:

答案 0 :(得分:1)

为了使用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;

如果您不将其设为受控输入,则可能可以使用ref来获取值。