Как изменить действие handleChange, основанное на вводе select, с помощью реакции? - PullRequest
0 голосов
/ 04 июля 2018

У меня есть некоторые действия handleChange, которые необходимо выбрать, при выборе этого действия будет запущено выбранное действие handleChange, ниже приведен код:

handleChange action:

handleEqualChange(event){
this.setState({
  equal: event.target.value,
 });
}

handleNotEqualChange(event){
this.setState({
  notequal: event.target.value,
 });
}

handleGreaterThanChange(event){
this.setState({
  greater_than: event.target.value,
 });
}

handleSmallerThanChange(event){
this.setState({
  smaller_than: event.target.value,
 });
}

handleGOEChange(event){
this.setState({
  goe: event.target.value,
 });
}

handleLOEChange(event){
this.setState({
  loe: event.target.value,
 });
}

Параметр выбора в раскрывающемся меню:

<select>
 <option value={this.state.equal}>Equal to</option>
 <option value={this.state.notequal}>Not equal to</option>
 <option value={this.state.greater_than}>Greater than</option>
 <option value={this.state.smaller_than}>Less than</option>
 <option value={this.state.goe}>Greater than or equal to</option>
 <option value={this.state.loe}>Less than or equal to</option>
</select>

Ввод текста:

<input className="col-md-1" type="text" placeholder="10" 
value={this.state.greater_than} onChange={this.handleGreaterThanChange} required/>

Я хочу передать значение текстового ввода в действие приставки, но оно всегда возвращается как значение {this.state.greater_than}, я хочу, чтобы при выборе {this.state.smaller_than} в параметре оно получило передать значение {this.state.smaller_than} и запустить действие {this.handleSmallerThanChange}, могу ли я знать, как это сделать? Спасибо.

Действие редукса, которое я делаю так:

export function createEvents(id, equal, notequal, greater_than, smaller_than, goe: goe, loe: loe, topic, email, contact) {
return (dispatch) => { // optionally you can have getState as the second argument
dispatch({
  type: EVENTS_CREATE_EVENTS_BEGIN,
});
const promise = new Promise((resolve, reject) => {
  // doRequest is a placeholder Promise. You should replace it with your own logic.
  // See the real-word example at:  https://github.com/supnate/rekit/blob/master/src/features/home/redux/fetchRedditReactjsList.js
  // args.error here is only for test coverage purpose.
  //const doRequest = args.error ? Promise.reject(new Error()) : Promise.resolve();
  axios.get('http://192.168.10.124:3000/api/Limits?filter[where][topic]=' + topic)
    .then(res => {
      console.log(res.data[0].id);

        axios.put('http://192.168.10.124:3000/api/Limits/' + res.data[0].id, { equal: equal, notequal: notequal, greater_than: greater_than, smaller_than: smaller_than, goe: goe, loe: loe, topic: topic, email: email, contact: contact }, {
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(
          (res) => {
            dispatch({
              type: EVENTS_CREATE_EVENTS_SUCCESS,
              data: res,
            });
            resolve(res);
            //window.location = '/events/events-page';
          },
          // Use rejectHandler as the second argument so that render errors won't be caught.
          (err) => {
            dispatch({
              type: EVENTS_CREATE_EVENTS_FAILURE,
              data: { error: err },
            });
            reject(err);
          },
        );
      });
    })
    .catch(err => {
      console.log(err);
    });

return promise;
};
}

Изменено действие handleChange:

handleChange(event){
console.log("Event.target.value is", event.target.value);
 this.setState({selectedOption: event.target.value});
  if(this.state.selectedOption=="equal"){
   this.setState({equal: event.target.value});
  };
  if(this.state.selectedOption=="notequal"){
   this.setState({notequal: event.target.value});
  };
  if(this.state.selectedOption=="greater_than"){
   this.setState({greater_than: event.target.value});
  };
  if(this.state.selectedOption=="smaller_than"){
   this.setState({smaller_than: event.target.value});
  };
  if(this.state.selectedOption=="goe"){
   this.setState({goe: event.target.value});
  };
  if(this.state.selectedOption=="loe"){
   this.setState({loe: event.target.value});
  };
}

1 Ответ

0 голосов
/ 04 июля 2018

Я думаю, вы не правильно обрабатываете выбор. Почему ваши значения параметров находятся в состоянии? Ваш выбор не имеет обработчика событий, и каково значение выбора? Почему у вас есть вход только с handleGreaterThanChange?

Тем не менее, вам нужно перевести в состояние выбранное значение и позволить селекту обработать изменение выбранного параметра.

Вот код:

class Hello extends React.Component {
    constructor(props){
    super(props);

    this.state = {
        selectedOption:"equal"
    }

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event){
    console.log("Event.target.value is", event.target.value);

    this.setState({selectedOption:event.target.value});
  }

  render() {
    return (
    <div>
       <select value={this.state.selectedOption} onChange={this.handleChange}>
         <option value={"equal"}>Equal to</option>
         <option value={"notequal"}>Not equal to</option>
         <option value={"greater_than"}>Greater than</option>
         <option value={"smaller_than"}>Less than</option>
         <option value={"goe"}>Greater than or equal to</option>
         <option value={"loe"}>Less than or equal to</option>
      </select>
    </div>
    );
  }
}

ReactDOM.render(
  <Hello/>,
  document.getElementById('container')
);

Вы можете попробовать это с этим jsFiddle .

...