简体   繁体   English

Jquery 更改函数未在 ReactJS 中正确更新变量?

[英]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 !!我正在使用 jquery 更改功能,但是当我更改输入值时,我得到了一个空字符串!! 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 :由于我看不到任何标记,因此我假设没有 ref 用于选择安装到DOM的元素,您必须执行以下操作:

  • Use a DOM ref instead of CSS selector.使用DOM ref 而不是CSS选择器。

  • Set the state inside the callback.在回调中设置状态。

Don't forget you can use onChange directly in your input element as well.不要忘记您也可以直接在输入元素中使用onChange

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:您应该将所有代码嵌套在change处理程序中,使用$(this).val()箭头更改处理程序来保留您的this范围,而不是从$(this).val()中提取您的值,您应该接受一个事件参数并使用e.target.value获取输入值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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