簡體   English   中英

提交后重置輸入字段

[英]Reset an input field after submission

我在redux-react應用程序中遇到一些處理簡單情況的問題:我希望在按鈕點燃異步操作后重置輸入文本。

假設我們有一個輸入文本,您可以在其中放置文本,並通過onClick事件傳遞給調度操作。 此操作與服務器聯系,在服務器響應后,我想重置輸入字段。

我已經實現了一些解決方案(我正在使用redux thunk)解決這個問題,但我不確定它們是否是解決它的黑客方法,讓我告訴你:

1)表示組件(輸入字段)實現一個重置方法,該方法作為值傳遞給onClick方法。

export default React.createClass({

  reset: function () {
    this.setState({searchText: ''})
  },

  getInitialState: function () {
    return {
      searchText: ''
    }
  },

  render: function () {
    return (
        <div>
          <TextField
            value={this.state.searchText}
            onChange={e => this.setState({ searchText: e.target.value })}
          />
          <RaisedButton
            onClick={this.props.startSearch.bind(null,
              this.state.searchText,
              this.reset)} // ===> HERE THE RESET FUNCTION IS PASSED
          />
        </div>
    )
  }
})

容器調度操作,然后調用reset方法。

const mapDispatchToProps = (dispatch) => {
  return {
    startSearch: (searchText, reset) => {
      dispatch(actions.startSearch(searchText))
      .then(() => reset())
    }
  }
}

2)使用ref( https://facebook.github.io/react/docs/refs-and-the-dom.html

容器獲取對其子項的引用,並通過它調用reset

const SearchUserContainer = React.createClass({

  startSearch: (searchText) => {
    dispatch(actions.startSearch(searchText))
    .then(() => this.child.reset())
  },

  render: function () {
    return (
      <SearchUser {...this.props} ref={(child) => { this.child = child; }}/>
    )
  }
})

3)Redux Way。

searchText由商店管理,因此調度的動作觸發了一個解析器,它重置了searchText值,容器更新了它的子代,我們完成了,嗯......幾乎:表示組件是一個受控組件( https://facebook.github.io /react/docs/forms.html#controlled-components )這意味着它將輸入文本作為內部狀態進行管理,我認為我們必須找到一種方法來使兩個“州經理”共存。

我編寫了這段代碼來管理來自redux的內部狀態和狀態,簡言之,表示從redux獲取初始值,然后在onChange事件中更新它,並且由於componentWillReceiveProps它已准備好從redux接收更新。

export default React.createClass({

  getInitialState: function () {
    return {
      searchText: this.props.searchText ==> REDUX
    }
  },

  componentWillReceiveProps: function (nextProps) {
    this.setState({
      searchText: nextProps.searchText ==> REDUX
    })
  },

  render: function () {
    return (
        <div>
          <TextField
            value={this.state.searchText}
            onChange={e => this.setState({ searchText: e.target.value })}
          />
          <RaisedButton
            onClick={this.props.startSearch.bind(null, this.state.searchText)}
          />
        </div>
    )
  }
})

4)Redux-Form為了完成圖片,我鏈接了redux-form選項來做到這一點http://redux-form.com/6.5.0/docs/faq/HowToClear.md/

您如何看待這些想法? 謝謝。

去Redux方式,除了一路:完全從組件中刪除內部狀態,讓Redux處理它(也可以使你的組件成為一個純功能組件):

零件:

import { connect } from 'redux';
import { actions } from 'actionCreators';

const ControlledInputComponent = (props) => {
  return (
    <div>
      <TextField
        value={this.props.searchText}
        onChange={e => this.props.setSearchText(e.target.value)}
      />
      <RaisedButton
        onClick={this.props.startSearch}
      />
    </div>
  );
};

const mapStateToProps = (state) => {
  return { searchText: state.searchText  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    setSearchText: (txt) => { dispatch(actions.setSearchText(txt)); },
    startSearch: () => { dispatch(actions.search()); }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ControlledInputComponent);  

行動創造者:

export const actions = {
  setSearchText: (txt) => ({ type: 'setText', data: txt }),

  //here's where the thunk comes in
  //make sure you have redux-thunk and add it as a middleware when setting up the store, etc.

  search: () => {
    return (dispatch) => {
      //use fetch or whatever to run your search (this is a simplified example)
      fetch(/* your url here */).then(() => {
        //presumably a success condition

        //handle the search results appropriately...

        //dispatch again to reset the search text
        dispatch(actions.setSearchText(null);
      });
    };
  }
};

減速器:

const reducer = (state = { searchText: null }, action) => {
  if (!action || !action.type) return state;
  switch (action.type) {

    //you should really define 'setText' as a constant somewhere
    //so you can import it and not have to worry about typos later
    case 'setText':
      return Object.assign({}, state, { searchText: action.data });

    default:
      return state;
  }
};

export default reducer;

希望這會有所幫助。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM