简体   繁体   中英

Jquery change function doesn't update variable correctly in ReactJS?

i'm using jquery change function but when i change input value i got an empty string !! this is my code any help plz :

 class SearchForm extends React.Component{ constructor(props) { super(props); this.state = {input_term_value: "",spaces_list: ""}; } componentDidMount() { var space_change_value = ""; $("input.sp-autocomplete-spaces").change(function() { space_change_value = $(this).val(); }); this.setState({spaces_list: space_change_value}); } updateInputValue(evt){ this.setState({input_term_value: evt.target.value}); } componentDidUpdate (prevProps, prevState) { this.sendGetRequest(); } sendGetRequest(){ var _this = this; this.serverRequest = axios

As I can't see any markup, I'll assume there's no ref used to select the element once mounted to the DOM , what you have to do :

  • Use a DOM ref instead of CSS selector.

  • Set the state inside the callback.

Don't forget you can use onChange directly in your input element as well.

You should nest all your code in the change handler, use a fat arrow change handler to preserve your this scope and instead of pulling your value from $(this).val() , you should be accepting an event param and use e.target.value to get the input value:

$("input.sp-autocomplete-spaces").change( e => {
    this.setState({ spaces_list: e.target.value });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM