最新antd-mobile Form表单使用setFieldsValue初始化表单

你不能用控件的 value 或 defaultValue 等属性来设置表单域的值,默认值可以用 Form 里的 initialValues 来设置。注意 initialValues 不能被 setState 动态更新,你需要用 setFieldsValue 来更新。

主要代码
一、第一种方法,推荐使用

const [form] = Form.useForm()
  useEffect(()=>{
    
    
     //defaultBaseInfo你的初始数据
    //监听defaultBaseInfo的变化,使用setFieldsValue来更新
    form.setFieldsValue(defaultBaseInfo)
  },[defaultBaseInfo])
  
  return (
    <div className="baby-info">
      <Form
        form={
    
    form}
        style={
    
    {
    
    
          '--border-inner': 'inherit',
          '--border-top': 'inherit',
          '--border-bottom': 'inherit',
        }}
        layout="horizontal"
        onFinish={
    
    onFinish}
        initialValues={
    
    defaultBaseInfo}
        footer={
    
    

二、第二种方法使用useRef

const initRef = useRef()
  useEffect(()=>{
    
    
    //监听defaultBaseInfo的变化,使用setFieldsValue来更新
     initRef.current.setFieldsValue(defaultBaseInfo)
  },[defaultBaseInfo])
  
  return (
    <div className="baby-info">
      <Form
        ref={
    
    initRef}
        style={
    
    {
    
    
          '--border-inner': 'inherit',
          '--border-top': 'inherit',
          '--border-bottom': 'inherit',
        }}
        layout="horizontal"
        onFinish={
    
    onFinish}
        initialValues={
    
    defaultBaseInfo}
        footer={
    
    

猜你喜欢

转载自blog.csdn.net/weixin_47541876/article/details/124339193
今日推荐