将额外的道具传递给包装在 FieldArray 中的组件(React)

Passing extra props to component wrapped in FieldArray (React)

我有一个 redux 表单,其中还有一个 FieldArray。 我将一个数组作为 name 传递并指向一个组件,该组件在 class 的主体之外定义为 component。非常简单:

...
return(
   <>
      <FieldArray name={myArray} component={emails}/>
   </>
)
...

这是emails

const emails = ({ fields }) => (
    <>
        <Table>
            <Table.Body>
                {fields.map((code, index) => (
                    <Table.Row>
                        <Table.Cell>
                            <Field
                                name={code}
                                type="text"
                                component={customInput}
                                autoFocus
                            />
                        </Table.Cell>
                        <Table.Cell>
                            <Button content='XXXXX'/>
                        </Table.Cell>

                    </Table.Row>
                ))}
            </Table.Body>
          </Table>
        <Button content='XXXXX' />
    </>
);

我想做的是将字典传递给 'emails' 以填充按钮的 'content' 字段(现在 XXXXX 所在的位置),因为它们来自一个翻译文件。

现在,查看 documentation,我可以看到他们提到了一个 'props' 参数。我试了一下就行了:

<FieldArray name={myArray} component={emails} props={myDictionary}/>

但我似乎无法真正将任何内容传递给 FieldArray(或者至少无法在另一端检索它)。 我看到了一些现有的问题,但重点似乎有点不同。

有没有人有这方面的经验或任何建议?谢谢:)

当您使用 React 创建功能组件时,您的组件接受 props 作为参数。

比如这段代码是:

const emails = ({ fields }) => {
    // do something with fields
    return <div></div>
}

等于:

const emails = (props) => {
    const {fields} = props;
    // do something with fields
    return <div></div>
}

因此,如果你通过

<FieldArray name={myArray} component={emails} myDictionary={myDictionary}/>

您将能够像这样访问它:

const FieldArray = (props) =>{
    const {myDictionary} = props;
}

您应该将对象传递给 props,它将与 emails 组件的 props 合并,因此如果您想使用 myDictionary 命名的 prop 获取它,您需要传递一个对象像这样

props={{ myDictionary: { test: 'test' } }}

你会得到

const emails = ({ fields, myDictionary }) => (

像这样:

return(
   <>
      <FieldArray name={myArray} component={emails} props={{ myDictionary: myDictionary }} />
   </>
)

const emails = ({ fields, myDictionary }) => (
    <>
        <Table>
            <Table.Body>
                {fields.map((code, index) => (
                    <Table.Row>
                        <Table.Cell>
                            <Field
                                name={code}
                                type="text"
                                component={customInput}
                                autoFocus
                            />
                        </Table.Cell>
                        <Table.Cell>
                            <Button content={myDictionary.test}/>
                        </Table.Cell>

                    </Table.Row>
                ))}
            </Table.Body>
          </Table>
        <Button content={myDictionary.test} />
    </>
);