132

作成、読み取り、更新、および削除に使用される 1 つのフォームを取得しました。同じフォームで 3 つのコンポーネントを作成しましたが、それらに異なる小道具を渡しました。CreateForm.js、ViewForm.js (削除ボタンで読み取り専用)、UpdateForm.js を取得しました。

以前は PHP を扱っていたので、これらは常に 1 つの形式で行っていました。

React と Redux を使用してストアを管理しています。

CreateForm コンポーネントを使用しているときは、サブコンポーネントにこの props を渡してcreateForm={true}、入力に値を入力せず、無効にしないようにします。私の ViewForm コンポーネントでは、この props を渡しますreadonly="readonly"

そして、値で満たされ、更新できないテキストエリアで別の問題が発生しました。値を持つ React textarea は読み取り専用ですが、更新する必要があります

フォームのこれらのさまざまな状態を処理するコンポーネントを 1 つだけ持つ最適な構造は何ですか?

共有するアドバイス、チュートリアル、ビデオ、デモはありますか?

4

4 に答える 4

115

Redux Formパッケージを見つけました。それは本当に良い仕事をします!

したがって、 React-ReduxでReduxを使用できます。

まず、フォーム コンポーネントを作成する必要があります (明らかに)。

import React from 'react';
import { reduxForm } from 'redux-form';
import validateContact from '../utils/validateContact';

class ContactForm extends React.Component {
  render() {
    const { fields: {name, address, phone}, handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <label>Name</label>
        <input type="text" {...name}/>
        {name.error && name.touched && <div>{name.error}</div>}

        <label>Address</label>
        <input type="text" {...address} />
        {address.error && address.touched && <div>{address.error}</div>}

        <label>Phone</label>
        <input type="text" {...phone}/>
        {phone.error && phone.touched && <div>{phone.error}</div>}

        <button onClick={handleSubmit}>Submit</button>
      </form>
    );
  }
}

ContactForm = reduxForm({
  form: 'contact',                      // the name of your form and the key to
                                        // where your form's state will be mounted
  fields: ['name', 'address', 'phone'], // a list of all your fields in your form
  validate: validateContact             // a synchronous validation function
})(ContactForm);

export default ContactForm;

この後、フォームを処理するコンポーネントを接続します。

import React from 'react';
import { connect } from 'react-redux';
import { initialize } from 'redux-form';
import ContactForm from './ContactForm.react';

class App extends React.Component {

  handleSubmit(data) {
    console.log('Submission received!', data);
    this.props.dispatch(initialize('contact', {})); // clear form
  }

  render() {
    return (
      <div id="app">
        <h1>App</h1>
        <ContactForm onSubmit={this.handleSubmit.bind(this)}/>
      </div>
    );
  }

}

export default connect()(App);

そして、結合されたレデューサーに redux-form レデューサーを追加します。

import { combineReducers } from 'redux';
import { appReducer } from './app-reducers';
import { reducer as formReducer } from 'redux-form';

let reducers = combineReducers({
  appReducer, form: formReducer // this is the form reducer
});

export default reducers;

バリデータ モジュールは次のようになります。

export default function validateContact(data, props) {
  const errors = {};
  if(!data.name) {
    errors.name = 'Required';
  }
  if(data.address && data.address.length > 50) {
    errors.address = 'Must be fewer than 50 characters';
  }
  if(!data.phone) {
    errors.phone = 'Required';
  } else if(!/\d{3}-\d{3}-\d{4}/.test(data.phone)) {
    errors.phone = 'Phone must match the form "999-999-9999"'
  }
  return errors;
}

フォームが完成した後、すべてのフィールドに値を入力したい場合は、次のinitialize関数を使用できます。

componentWillMount() {
  this.props.dispatch(initialize('contact', {
    name: 'test'
  }, ['name', 'address', 'phone']));
}

フォームに入力する別の方法は、initialValues を設定することです。

ContactForm = reduxForm({
  form: 'contact',                      // the name of your form and the key to
  fields: ['name', 'address', 'phone'], // a list of all your fields in your form
  validate: validateContact             // a synchronous validation function
}, state => ({
  initialValues: {
    name: state.user.name,
    address: state.user.address,
    phone: state.user.phone,
  },
}))(ContactForm);

これを処理する他の方法がある場合は、メッセージを残してください。ありがとうございました。

于 2015-10-28T14:15:43.390 に答える
11

更新: その 2018 年、私はFormik (または Formik のようなライブラリ)のみを使用します。

react-redux-form ( step-by-step )もありますが、これはredux-formの javascript (&ボイラープレート) の一部をマークアップ宣言と交換しているようです。良さそうですが、まだ使っていません。

readme からのカット アンド ペースト:

import React from 'react';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { modelReducer, formReducer } from 'react-redux-form';

import MyForm from './components/my-form-component';

const store = createStore(combineReducers({
  user: modelReducer('user', { name: '' }),
  userForm: formReducer('user')
}));

class App extends React.Component {
  render() {
    return (
      <Provider store={ store }>
        <MyForm />
      </Provider>
    );
  }
}

./components/my-form-component.js

import React from 'react';
import { connect } from 'react-redux';
import { Field, Form } from 'react-redux-form';

class MyForm extends React.Component {
  handleSubmit(val) {
    // Do anything you want with the form value
    console.log(val);
  }

  render() {
    let { user } = this.props;

    return (
      <Form model="user" onSubmit={(val) => this.handleSubmit(val)}>
        <h1>Hello, { user.name }!</h1>
        <Field model="user.name">
          <input type="text" />
        </Field>
        <button>Submit!</button>
      </Form>
    );
  }
}

export default connect(state => ({ user: state.user }))(MyForm);

編集:比較

react-redux-form ドキュメントは redux-form との比較を提供します:

https://davidkpiano.github.io/react-redux-form/docs/guides/compare-redux-form.html

于 2016-06-02T11:06:51.397 に答える
4

フォーム関連の問題を処理するための膨大なライブラリを気にしない人には、redux-form-utilsをお勧めします。

フォーム コントロールの値と変更ハンドラーを生成したり、フォームのレデューサーを生成したり、特定の (またはすべての) フィールドをクリアする便利なアクション クリエーターを生成したりできます。

コードでそれらを組み立てるだけです。

を使用するredux-form-utilsと、次のようなフォーム操作になります。

import { createForm } from 'redux-form-utils';

@createForm({
  form: 'my-form',
  fields: ['name', 'address', 'gender']
})
class Form extends React.Component {
  render() {
    const { name, address, gender } = this.props.fields;
    return (
      <form className="form">
        <input name="name" {...name} />
        <input name="address" {...address} />
        <select {...gender}>
          <option value="male" />
          <option value="female" />
        </select>
      </form>
    );
  }
}

ただし、このライブラリは問題を解決するだけでCありU、 、RおよびについてDは、より統合されたTableコンポーネントが予測される可能性があります。

于 2016-06-07T09:14:48.140 に答える