在提交前更改/更改表单值

问题描述 投票:0回答:1

我们正在使用react-admin react-admin docs

我有一个带有字段productName, Price and Image的表格。图片字段具有字符串类型,这意味着将图片上传到s3或任何其他目标,并将上传的图片URL动态传递到图片字段。

我具有将图片上传到s3的功能,现在我将获得s3 URL,用户将填写ProductName and Price字段并点击Submit。当表单提交时,我也希望将图像URL传递给其他字段。

以上是我要达到的要求。让我向您解释我的尝试。

我正在关注此链接link

ProductCreate.js

export class ProductCreate extends Component{

render(){

    return (
        <Create {...this.props}>
            <SimpleForm toolbar={<PostCreateToolbar />} redirect="show">                    
                <TextInput source="name" />
                <TextInput source="price"/>
            </SimpleForm>
        </Create>
    )
}
}

在上面的代码中,您可以看到我在toolbar上使用了SimpleForm道具,并使用了名为PostCreateToolbar的自定义工具栏。

PostCreateToolbar.js

const PostCreateToolbar = props => (
<Toolbar {...props}>
    <SaveWithNoteButtonView
        label="Save"
        redirect="show"
        submitOnEnter={false}
        variant="contained"
    />
</Toolbar>
);

SaveWithNoteButtonView.js

class SaveWithNoteButtonView extends Component {    

handleClick = () => {
    const { basePath, handleSubmit, redirect } = this.props;

    const form = useForm();

    console.log("123", this.props);
    return handleSubmit(values => {
        console.log("456", this.props);
        crudCreate('posts', { ...values, imageUrl: "https://s3.us-east-1.amazonaws.com/..." }, basePath, redirectTo);
    });
};

render() {
    const { handleSubmitWithRedirect, saveWithNote, ...props } = this.props;

    return (
        <SaveButton
        handleSubmitWithRedirect={this.handleClick}
        {...props}
        />
        );
    }
}

SaveWithNoteButtonView文件中,您可以看到我具有handleClick函数,当用户单击保存按钮时,将调用此函数,但未调用handleSubmit。当用户单击保存按钮时,我可以看到第一个控制台,但看不到handleSubmit内的第二个控制台。可能是API调用发生时无法发送imageUrl字段的问题。

任何人都可以通过其他方式传递自定义数据,然后再提交,我很乐意了解。

另一种方法,我认为是在产品形式中,我可以禁用imageURL字段,当图像上传到s3并获取URL时,以某种方式用imageURL值填充imageURL字段。因此,当我们提交表单imageURL字段值时,将其传递给api。如果您知道如何实现这一点,它将很有用。

reactjs react-admin
1个回答
0
投票

为什么使用类而不是函数? useForm是一个挂钩,必须在功能组件内部使用。

再次检查他们的示例。 useForm处理表单的数据。尝试使用console.log(form),也可以使用useForm方法.change()来更改其值,然后再提交。

如果您按照相应的示例操作,它们的示例将非常适用。尝试模拟他们的代码,并仅更改要添加的图像值。您不应该使用CRUDcreate,因为react-admin会自动处理保存。

© www.soinside.com 2019 - 2024. All rights reserved.