You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Admin on Rest的Create表单中通过其他组件修改输入框值?

在Admin on Rest中实现点击按钮设置输入框值且不提交表单

这个需求其实很好解决,核心是借助Admin on Rest底层依赖的redux-form提供的change action来修改表单字段的值,同时阻止按钮触发表单的默认提交行为。下面是具体的实现步骤和代码示例:

步骤1:导入所需依赖

首先需要导入Admin on Rest的组件、redux-form的change action,以及react-redux的连接工具(或者Hooks):

import React from 'react';
import { Create, SimpleForm, TextInput, Button } from 'admin-on-rest';
import { change } from 'redux-form';
import { connect } from 'react-redux'; // 兼容无Hooks的旧版本场景
// 如果用React Hooks,换成 import { useDispatch } from 'react-redux';

步骤2:创建自定义Create组件

我们需要在Create表单中添加自定义按钮,并处理点击事件:

方式一:使用connect绑定dispatch(兼容旧版本)

const CustomCreate = ({ dispatch, ...props }) => {
    const handleSetHello = (e) => {
        e.preventDefault(); // 关键:阻止按钮触发表单默认提交
        // 调用redux-form的change action修改字段值
        // 参数说明:'record-form'是Admin on Rest默认的Create表单名称,'yourFieldName'对应TextInput的source属性,最后是要设置的值
        dispatch(change('record-form', 'yourFieldName', 'Hello'));
    };

    return (
        <Create {...props}>
            <SimpleForm>
                {/* 你的输入框,source要和上面的字段名对应 */}
                <TextInput source="yourFieldName" />
                {/* 自定义按钮,绑定点击事件 */}
                <Button onClick={handleSetHello} label="Set to Hello" />
                {/* 如果需要保留默认的提交按钮,可以加上 */}
                <Button type="submit" label="Submit" />
            </SimpleForm>
        </Create>
    );
};

// 用connect把dispatch注入组件
export default connect()(CustomCreate);

方式二:使用React Hooks(更简洁,适合新版本)

如果你的项目支持React Hooks,可以用useDispatch来简化代码:

import React from 'react';
import { Create, SimpleForm, TextInput, Button } from 'admin-on-rest';
import { change } from 'redux-form';
import { useDispatch } from 'react-redux';

const CustomCreate = (props) => {
    const dispatch = useDispatch();

    const handleSetHello = (e) => {
        e.preventDefault();
        dispatch(change('record-form', 'yourFieldName', 'Hello'));
    };

    return (
        <Create {...props}>
            <SimpleForm>
                <TextInput source="yourFieldName" />
                <Button onClick={handleSetHello} label="Set to Hello" />
                <Button type="submit" label="Submit" />
            </SimpleForm>
        </Create>
    );
};

export default CustomCreate;

关键说明

  • 阻止默认提交:一定要调用e.preventDefault(),否则按钮会触发表单的提交流程,这不是我们想要的。
  • 表单名称:Admin on Rest中Create表单的默认名称是record-form,如果你的表单自定义了名称,需要替换成对应的名字。
  • 字段对应:change action的第二个参数必须和TextInput的source属性完全一致,这样才能正确修改对应输入框的值。

这样点击"Set to Hello"按钮时,输入框就会被设置为"Hello",同时不会触发表单提交,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Andy Cochrane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:19:43