代码之家  ›  专栏  ›  技术社区  ›  joedotnot

react final form字段如何访问一些初始值?

  •  2
  • joedotnot  · 技术社区  · 6 年前

    假设我的 应用程序 组件看起来像:

    import { Form } from "react-final-form";
    
    myInitData = {
        firstName: "akira",
        lastName: "fubuki"
    }
    
    render() {
        return 
            <Form
                initialValues={myInitData} 
                onSubmit={this.handleSubmit}
                validate={this.validate}
              >
                    {({handleSubmit, submitting, values}) => (
    
                        <MyComponentOuter
                            someProp1={100}
                            someProp2={200}
                        />
    
                    )}
            </Form>
    }
    

    此外,我还有一些组件 支原体 在内部 MycomponentOuter公司 所以层次结构是app=>mycomponentouter=>mycomponentinner

    支原体 看起来像:

    class MyComponentInner extends Component {
    
        componentDidMount() {
            console.log(????) //how do i get access to firstName here..?
        }
        render() {
            return (
    
                <label>first name</label>
                <Field
                  name="firstName"
                  component="input"
                  type="text"
                />
            )
        }
    }
    

    我的问题是:

    a)react final form的组件如何自动访问“firstname”属性?(没有明确传递道具)。

    b)我想在mycomponentinner中访问相同的firstname值;语法是什么,例如,如果我想console.log firstname。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Erik R.    6 年前

    a)它使用 React context 是的。这个 <Form> 组件包含 final-form 为您管理所有窗体状态的对象,以及 <Field> 组件使用 context 与形态状态对话。

    b)这样的事情就行了。提供给 Field 提供了所有这些 FieldRenderProps 是的。

    <Field name="firstName">
      {
        ({ input } /* FieldRenderProps */) => {
          console.log(input.value)
          return null // render nothing (this is a render function)
        }
      }
    </Field>
    
    推荐文章