2017-03-24 6 views
0

formsy-material-uiのコンポーネントの最初の検証を遅らせることができるので、isNotEmptyのような検証はフォームの最初のレンダリングで起動せず、UXを混乱させませんか?私は制御されたコンポーネントを使用しているので、各レンダーの状態から値を設定しています。Formsy-material-uiは初期レンダリングを検証しません

<FormsyText 
    name="name" 
    value={this.state.name} 
    floatingLabelText="Name" 
    onChange={partial(this._changeInputValue, ['name'])} 
    validations={{ isNotEmpty }} 
    validationError="Field shoud not be empty" 
/> 

答えて

0

この解決策も必要でした。私はformsy-material-uiのソースコードを調べています。テキストフィールドは、マウントされる前にその値を設定しているようです。そのため、レンダリングが行われたときにフィールドが変更された(原始ではない)とマークされているため、検証エラーが表示されます。

とにかく、私はより高次のコンポーネントを使ってハッキリした解決策を書いていました。テキストフィールドのみでテストしていますが、この問題が発生しているフィールドで作業する必要があります。コアコンセプト:フォームフィールドに「validationErrors」小道具がない場合、エラーは表示されません。それを使用する方法

import React, { Component, PropTypes } from 'react'; 

export const preventFirstValidation = (FormsyField) => { 
    return class extends Component { 
    static propTypes = { preventFirstValidation: PropTypes.bool }; 
    static defaultProps = { preventFirstValidation: true }; 

    constructor(props) { 
     super(props); 
     this.state = { isChanged: false }; 
    } 

    render() { 
     const { preventFirstValidation, ...fieldProps } = this.props; 
     return (
     <FormsyField 
      {...fieldProps} 
      onChange={(evt, val) => { 
      if (!this.state.isChanged) this.setState({ isChanged: true }); 
      if (this.props.onChange) this.props.onChange(evt, val); 
      }} 
      validationErrors={(this.state.isChanged || !preventFirstValidation) ? this.props.validationErrors : undefined} 
     /> 
    ); 
    } 
    }; 
}; 

import { Form } from 'formsy-react'; 
import FormsyTextField from 'formsy-material-ui/lib/FormsyText'; 

const TextField = preventFirstValidation(FormsyTextField); 

const MyForm =() => (
    <Form> 
    {/* You're using the transformed field, exactly like before */} 
    <TextField 
     name = "some_field" 
     validationErrors={{ isRequired: 'This is really required!' }} 
     required 
     preventFirstValidation={ /* you can enable or disable this feature */ } 
    /> 
    </Form> 
); 
関連する問題