【问题标题】:How to change TextInput values using FormDataConsumer如何使用 FormDataConsumer 更改 TextInput 值
【发布时间】:2019-09-15 08:32:37
【问题描述】:

我在尝试使用 FormDataConsumer 根据另一个输入动态更改 TextInput 值时遇到了一些麻烦。

我有一个 ReferenceInput,它设置了一个 AutocompleteInput,其中包含一些选项,如下所示:

<ReferenceInput id="nome" label="Portaauto" source="Portaauto" name="Portaauto" reference="acl-pegaProtocolosConhecidos" alwaysOn >
    <AutocompleteInput id="protocolo" name="Portaautoinput" source="protocolo" translateChoice={false} optionText="nome" />
</ReferenceInput>

后端返回这条记录:

[{"id":"http","nome":"http(80)","porta":"80","protocolo":"tcp"},
{"id":"https","nome":"https(443)","porta":"443","protocolo":"tcp"},
{"id":"ntp","nome":"ntp(123)","porta":"123","protocolo":"udp"},
{"id":"dns","nome":"dns(53)","porta":"53","protocolo":"udp"},
{"id":"custom","nome":"custom(10-100)","porta":"10-100","protocolo":"gre"}]

此输入按预期工作,但我需要使用用户选择更改其他 2 个输入。所以,如果用户选择“http”,一个输入需要有“80”,另一个输入需要有“tcp”。

我尝试以简单的方式仅更改一个输入,但我什至无法使用以下代码动态设置 TextInput 值:

const getPortSugestion = (values) => {
    console.log(values)
    return values
};

<FormDataConsumer id="nome">
                {({ formData, record, ...rest }) =>
                    <TextInput
                        name="city"
                        source={getPortSugestion(formData.Portaauto)}
                        value={getPortSugestion(formData.Portaauto)}
                        {...rest}
                    />
                }
</FormDataConsumer>

使用此代码,“源”会更改(使用“nome”),但“值”不会更改...

那么,如何更改 TextInput 的值?

我如何访问记录中的其他属性,以便使用记录中的其他字段(“porta”和“protocolo”)更改输入值?

有人可以帮忙吗?提前致谢。

【问题讨论】:

    标签: react-admin


    【解决方案1】:

    我刚刚尝试过,它对我有用...这不是您的确切代码,但概念是相同的,应该对您有用,如果不发回您尝试过的内容,我会修改我的示例。

    <TextInput source="dynamic" />
    <AutocompleteInput source="category" choices={[
        { id: 'programming', name: 'Programming' },
        { id: 'lifestyle', name: 'Lifestyle' },
        { id: 'photography', name: 'Photography' },
    ]} />
    
    <FormDataConsumer>
        {({formData, dispatch, ...rest}) => {
            console.log(formData.category);
            if (formData.category && formData.category === 'programming') {
                return (
                    formData.dynamic="bang"
                );
            }
        }}
    </FormDataConsumer>
    

    有趣的是,我记得有这个问题但没有让它工作,所以我做了一些不同的事情,但是当我看到你的问题时我想我会重新审视..

    【讨论】:

    • 不错的解决方案!但我认为这还不够,因为我需要访问记录中的其他字段...
    【解决方案2】:

    无法访问用户选择的完整记录是我对 RA 最大的痛苦之一。因此,我制作了自己的 CustomAutocomplete,它允许我抓取所选的完整记录并将其存储到状态中。

    如果您想重新创建,这是您需要进行的唯一更改。

    YourCustomAutocomplete.js

    handleSuggestionSelected = (event, { suggestion, method }) => {
        const { input, getSelected } = this.props;
    
        const inputValue = this.getSuggestionValue(suggestion);
        if (input && input.onChange) {
            input.onChange(inputValue);
        }
    
        if(getSelected) {
            getSelected(suggestion);
        }
    
        if (method === 'enter') {
            event.preventDefault();
        }
    };
    

    然后在您的表单或表单组件中具有将存储到状态的基本功能:

    YourForm.js

        getSelected = selectedItem => {
        this.setState({ selectedItem });
      };
    
    
                 <AutocompleteInput
                    inputValueMatcher={inputValueMatcher}
                    shouldRenderSuggestions={(val) => {return val.trim().length > 2}}
                    limitChoicesToValue={true}
                    optionText="name"
                    getSelected={this.getSelected}
                />
    

    现在可以使用redux-form的change函数as detailed in RA's docs了。

    所以对我来说,我让用户为账单选择供应商,我将该供应商的数据存储到状态中,然后进行几次更改调用,自动为用户设置供应商信息。

    【讨论】:

    • 谢谢!我稍后再试!
    【解决方案3】:

    好吧,我使用了这样的解决方案:react-admin - How to set input values based on another

    const customOnChange = (event)=>{
        const tokenSessionItem = "oidc.user:" + OidcSettings.authority + ":" + OidcSettings.client_id;
        const token = sessionStorage.getItem(tokenSessionItem);
    
        if (event.Portaauto) {
            if (event.Portaauto !== formBeforeState_Portaauto) {
                const toFetch = dataProviderURL + `/getProtocols/${event.Portaauto}`;
                fetch(toFetch, { method: 'GET', headers: {'content-type': 'application/json', 'Authorization' : `${token}`}})
                .then(response => response.json())
                .then(data => {
                    //console.log(data[0].id)
                    event.porta = data[0].porta
                    event.protocolo = data[0].protocolo
                });
                formBeforeState_Portaauto = event.Portaauto 
            }
        }
    }
    

    表格:

    export const AcladvCreate = props => (
        <Create {...props}>
            <SimpleForm onChange={customOnChange}>
                  <CustomProtocolSugestion />
            </SimpleForm>
        </Create>
    

    自定义元素:

    Class CustomProtocolSugestion extends React.Component {
        render() {
            return (
                <div>   
                        <div>
                            <FormDataConsumer>
                            {({ formData, ...rest }) => (
                                formData.protocolo !== "ip" ?
                                <TextInput source="porta" label="Porta" validate={validaPorta} />
                                : null
                            )}
                            </FormDataConsumer>
                        </div>
    
                        <ReferenceInput id="protocolo" label="Protocolo" source="protocolo" reference="acl-protocolosPermitidos" resource="acl-protocolosPermitidos" style={hiddenSelectStylePre}>
                            <SelectInput translateChoice={false} optionText="id"/>
                        </ReferenceInput>
    
                        <ReferenceInput id="Portaauto" label="?" source="Portaauto" reference="acl-pegaProtocolosConhecidos" resource="acl-pegaProtocolosConhecidos" allowEmpty style={hiddenSelectStyleCurrSelect} >
                            <SelectInput translateChoice={false} optionText="id" />
                        </ReferenceInput>
    
    
                </div>
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多