如何从另一个 javascript 文件手动调用 react 处理程序?
import './external/myPlugin'
class Title extends Component {
@autobind
setTitle(e) {
// do something
}
render() {
return (<Textarea className="parent" value="default" onChange={this.setTitle} />);
}
}
//这里是普通的 javascript 文件。 (会被window.open打开)
var titleElement = window.opener.document.getElementsByClassName("parent")[0]
titleElement.value = "this is the new title";
如何调用'handleChangeTitle'函数?
//我试过了。但它不起作用...
titleElement.dispatchEvent(new Event('change', { bubbles: true}));
titleElement.dispatchEvent(new Event('input', { bubbles: true}));
titleElement.dispatchEvent(new Event('textarea', { bubbles: true}));
最佳答案
显然,如果您有任何选择,请找到一种不同的方法来解决不需要从外部触发事件处理程序的潜在问题。 :-)
我发现的唯一方法是挂接到 DOM 事件并将其转发到 setTitle
。这是一个示例(主要参见 ***
注释):
class Title extends React.Component {
constructor(props) {
super(props);
this.state = {
title: ""
};
// *** A ref so we can access the DOM element
this.titleRef = React.createRef();
this.setTitle = this.setTitle.bind(this);
}
componentDidMount() {
// ** Hook the input event on the DOM element
if (this.titleRef.current) {
this.titleRef.current.addEventListener("input", this.setTitle);
}
}
componentWillUnmount() {
// *** Release the input event on the DOM element
if (this.titleRef.current) {
this.titleRef.current.removeEventListener("input", this.setTitle);
}
}
setTitle({target: {value: title}}) {
// *** Update the title. Note that if the user types in the element and React
// fires its event, you'll get two events (one from React, another from the DOM).
// If you need to do something other than setting state in this method, check
// first to see if the new title and the old are identical. But there's no need
// if you're just calling `setState`, it will ignore an unnecessary state change.
console.log(`setTitle: ${e.target.value}`);
this.setState({title: e.target.value});
}
render() {
// *** Use the current title as the value, use the ref
const {title} = this.state;
return (<textarea id="example" ref={this.titleRef} className="parent" value={title} onChange={this.setTitle} />);
}
}
ReactDOM.render(<Title/>, document.getElementById("root"));
setTimeout(function() {
const example = document.getElementById("example");
example.value = "updated";
example.dispatchEvent(new Event('change', { bubbles: true}));
example.dispatchEvent(new Event('input', { bubbles: true}));
}, 800);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
不过,如果您能找到一种方法来避免首先从外部触发事件处理程序,那么我会这样做。
关于javascript - 如何从另一个 javascript 文件手动调用 react 处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58449008/