UNPKG

@aliretail/react-materials-components

Version:
146 lines (128 loc) 3.67 kB
--- title: 自定义组件demo order: 0 --- # 自定义组件 demo 这里模拟一个自定义组件注册到全局 form 中 如果只需要注册到一个 form 表单中,请使用 SchemaForm 中的 components 配置 ### 下面是一个获得随机数的自定义组件 一个自定义组件需要有几个固定 props: onChange 和 value value 就是表单中相应的值,onChange 方法的入参就是你需要改变的这个表单项的值 可以打开控制台查看表单的数值修改 ```jsx import React, { useState } from 'react'; import ReactDOM from 'react-dom'; import { Button } from '@alife/next'; import { FormComponents } from '@aliretail/react-materials-components'; const { setup, SchemaForm, connect } = FormComponents; // 模拟一个获取随机数据的组件 const CustomCom = (props) => { const { value, onChange, readOnly, isPreview, disabled } = props; return ( <> <div style={{ border: '1px solid #cf3f25' }}> {value} {!readOnly && !isPreview && !disabled && ( <Button onClick={() => { onChange(Math.random()); }} > 获得随机数字 </Button> )} </div> </> ); }; setup({ CustomCom: connect({})(CustomCom), }); const App = () => { const [editable, setEditable] = useState(true); const [isPreview, setPreview] = useState(false); const [disabled, setDisabled] = useState(false); const extConfig = { isPreview, disabled, }; return ( <> <SchemaForm defaultValue={{ onlySetWidth: 0, }} editable={editable} // 监听内容修改 onChange={console.log} schema={{ type: 'object', properties: { gridLayout: { type: 'object', 'x-component': 'GridLayout', 'x-component-props': { isForm: true, align: 'left', }, properties: { onlySetWidth: { title: '宽度设置', required: true, 'x-component': 'CustomCom', 'retail-form-item-props': { inputAreaWidth: '50%', inputAreaWidthFixed: true, }, itemClassName: 'onlySetWidth1', className: 'onlySetWidth', itemStyle: { background: '#ddd' }, 'x-component-props': { ...extConfig, }, }, }, }, }, }} /> <div style={{ marginTop: 40 }}> <Button text type="primary" style={{ marginRight: 10 }} onClick={() => { setEditable(!editable); }} disabled={isPreview || disabled} > 切换{editable ? 'readonly' : '编辑'}状态 </Button> <Button text type="primary" style={{ marginRight: 10 }} onClick={() => { setPreview(!isPreview); }} disabled={!editable || disabled} > 切换{isPreview ? '编辑' : 'isPreview'}状态 </Button> <Button text type="primary" style={{ marginRight: 10 }} onClick={() => { setDisabled(!disabled); }} disabled={!editable || isPreview} > 切换{disabled | isPreview ? '编辑' : 'disabled'}状态 </Button> </div> </> ); }; ReactDOM.render(<App />, mountNode); ```