【问题标题】:react-final-form how does Field access some initial value?react-final-form Field 如何访问一些初始值?
【发布时间】:2018-07-18 10:39:43
【问题描述】:

假设我的 App 组件如下所示:

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 中有一些组件 MyComponentInner 所以层次结构是 App => MyComponentOuter => MyComponentInner

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.

【问题讨论】:

    标签: reactjs react-final-form


    【解决方案1】:

    a) 它使用React context&lt;Form&gt; 组件包含一个 final-form 对象,它为您管理所有表单状态,&lt;Field&gt; 组件使用 context 与表单状态对话。

    b) 这样的事情就可以了。所有这些FieldRenderProps 都提供给Field 的渲染函数。

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

    【讨论】:

    • 非常感谢您的回复。为了清楚起见,所以我无法在 之外提取底层的 firstName 值,就像我在 componentDidMount() 内的问题中尝试做的那样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2020-11-16
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多