如何以编程方式填充使用React构建的输入元素? [英] How to programmatically fill input elements built with React?

查看:68
本文介绍了如何以编程方式填充使用React构建的输入元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是使用React构建的抓取网站.我正在尝试填写输入字段,并使用javascript注入页面(移动设备中的selenium或webview)来提交表单.在其他所有站点和技术上,它都像魅力一样起作用,但是React似乎是一个真正的痛苦.

I'm tasked with crawling website built with React. I'm trying to fill in input fields and submitting the form using javascript injects to the page (either selenium or webview in mobile). This works like a charm on every other site + technology but React seems to be a real pain.

这是示例代码

var email = document.getElementById( 'email' );
email.value = 'example@mail.com';

我的值在DOM输入元素上发生了变化,但是React不会触发更改事件.

I the value changes on the DOM input element, but the React does not trigger the change event.

我一直在尝试多种不同的方法来使React更新状态.

I've been trying plethora of different ways to get the React to update the state.

var event = new Event('change', { bubbles: true });
email.dispatchEvent( event );

无济于事

var event = new Event('input', { bubbles: true });
email.dispatchEvent( event );

不起作用

email.onChange( event );

不起作用

我不敢相信与React的互动变得如此困难.我将不胜感激任何帮助.

I cannot believe interacting with React has been made so difficult. I would greatly appreciate any help.

谢谢

推荐答案

React正在侦听文本字段的input事件.

React is listening for the input event of text fields.

您可以更改值并手动触发输入事件,然后react的onChange处理程序将触发:

You can change the value and manually trigger an input event, and react's onChange handler will trigger:

class Form extends React.Component {
  constructor(props) {
    super(props)
    this.state = {value: ''}
  }
  
  handleChange(e) {
    this.setState({value: e.target.value})
    console.log('State updated to ', e.target.value);
  }
  
  render() {
    return (
      <div>
        <input
          id='textfield'
          value={this.state.value}
          onChange={this.handleChange.bind(this)}
        />
        <p>{this.state.value}</p>
      </div>      
    )
  }
}

ReactDOM.render(
  <Form />,
  document.getElementById('app')
)

document.getElementById('textfield').value = 'foo'
const event = new Event('input', { bubbles: true })
document.getElementById('textfield').dispatchEvent(event)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'></div>

这篇关于如何以编程方式填充使用React构建的输入元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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