如何在Admin-on-Rest中默认选中SelectInput的第一个选项
我之前在Admin-on-Rest开发时也碰到过一模一样的问题,SelectInput默认选中第一个选项的需求看起来简单,但因为它依赖redux-form的表单状态管理,直接靠组件自身属性经常不生效。给你几个亲测有效的解决方案:
方案1:给表单设置initialValues
这是最直接有效的方法,因为Admin-on-Rest的表单状态由redux-form管控,组件的选中状态完全依赖表单的初始值,而不是choices数组的顺序。你只需要在包裹SelectInput的表单组件(比如SimpleForm或TabbedForm)上添加initialValues属性,指定existing_user的初始值为'existing':
<SimpleForm initialValues={{ existing_user: 'existing' }}> <SelectInput source="existing_user" choices={[ { id: 'existing', name: 'Existing'}, { id: 'new', name: 'New User' }, ]} validate={required} /> {/* 你的DependInput组件 */} </SimpleForm>
这样表单加载时,redux-form会自动把existing_user设为'existing',SelectInput就会默认选中第一个选项,DependInput也能根据这个值正常渲染关联字段了。
方案2:处理编辑页面的空数据场景
如果是在编辑页面(Edit组件)遇到这个问题,可能是因为后端返回的数据里没有existing_user字段,导致表单初始值为空。这时候可以通过transform属性在获取数据后补充默认值:
<Edit transform={data => ({ ...data, // 如果数据里没有existing_user,就默认设为'existing' existing_user: data.existing_user || 'existing' })} > <SimpleForm> <SelectInput source="existing_user" choices={[ { id: 'existing', name: 'Existing'}, { id: 'new', name: 'New User' }, ]} validate={required} /> {/* 你的DependInput组件 */} </SimpleForm> </Edit>
这个方法能确保不管后端有没有返回该字段,表单都会有一个合法的初始值,避免SelectInput为空的情况。
为什么直接设置组件属性不生效?
你之前尝试设置底层Select的属性没用,是因为Admin-on-Rest的SelectInput是基于react-select封装的,但它的状态完全由redux-form接管,组件自身的defaultValue等属性会被表单状态覆盖。所以必须通过redux-form提供的initialValues或者数据转换来设置初始值,才能让选中状态生效。
内容的提问来源于stack exchange,提问作者HakoneMatate

