使用javascript(Tampermonkey脚本)将文本输入到React输入中?

问题描述 投票:0回答:2

我正在尝试制作一个Tampermonkey脚本,它会自动将文本输入到某些表单输入字段中。

通常情况下,你可以这样做:

myElement.value = "my new text"

问题是,这个表单正在使用React,我无法直接更改该值,因为它没有设置React状态。如何在我的Tampermonkey脚本中将我想要的数据输入到这些React组件中?

javascript reactjs tampermonkey
2个回答
1
投票

React不公开组件实例,因此如果可能的话,在初始化时不会篡改应用程序就无法访问它们。

通过发出DOM事件,输入值应该像使用vanilla JavaScript一样进行更改。

React提供了具有辅助函数的utility library

这是an example。输入:

<input id="input" value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />

在React应用程序初始化之后运行的用户脚本:

import { Simulate } from 'react-dom/test-utils';

const input = document.getElementById('input');
input.value = 'Foo';
Simulate.change(input);

0
投票
class HelloWorld extends React.Component{
  constructor(props){
    super(props);
    this.state = {firstname: ''};
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(e){
   this.setState({firstname: e.target.value})
  }
  render(){
   return(<div><input id="firstname" type=text onChange={(e) =>this.handleChange()} value={this.state.firstname} ></div>) 
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.