从JavaScript或JQuery设置React输入字段值 [英] Set React Input Field Value from JavaScript or JQuery

查看:420
本文介绍了从JavaScript或JQuery设置React输入字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过香草JS或JQuery以编程方式设置React生成的输入字段的值?

How can you programmatically set the value of an input field generated by React, either with vanilla JS or JQuery?

我尝试了以下操作,但似乎没有任何效果.

I've tried the following and nothing seems to work.

$(obj).val('abc');
$(obj).attr('value', 'abc');
$(obj).keydown();
$(obj).keypress();
$(obj).keyup();
$(obj).blur();
$(obj).change();
$(obj).focus();

我还尝试模拟keyPress(如建议的此处)事件但这似乎也不起作用.

I've also tried to simulate keyPress (as suggested here) events but it doesn't seem to work either.

simulateKeyPresses (characters, ...args) {
  for (let i = 0; i < characters.length; i++) {
    this.simulate('keyPress', extend({
      which: characters.charCodeAt(i),
      key: characters[i],
      keyCode: characters.charCodeAt(i)
    }, args));
  }
}

推荐答案

As showcased in the react test utils docs in the simulate section, you can see what they're basically doing is changing the DOM node value and then triggering an input event.

您可以执行以下操作,并使用输入的DOM元素和新值对其进行调用.

What you could do is something like the following, calling it with your input DOM element and new value.

const changeValue = (element, value) => {
  const event = new Event('input', { bubbles: true })
  element.value = value
  element.dispatchEvent(event)
}

但是取决于您如何定义组件,例如,如果您期望输入Enter键,则必须调度匹配事件.

Depends on how you defined your components though, if for example you're expecting an enter keypress, you'll have to dispatch the matching event.

这篇关于从JavaScript或JQuery设置React输入字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆