作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在使用 React 构建一个简单的静态 View 引擎,目标是呈现静态 HTML 标记并生成一个填充了该组件 DOM 事件(onClick 等)的 js 文件。
我做第一部分的方式是要求一个指定的 JSX 文件,例如,它看起来像这样:
import React from 'React';
export default class Test extends React.Component {
clicked() {
alert('Clicked the header!');
}
render() {
return (
<html>
<head>
<title>{this.props.title}</title>
</head>
<body>
<h1 onClick={this.clicked}>click me!!!</h1>
</body>
</html>
);
}
}
然后我通过 NodeJS 后端渲染 JSX 文件,如下所示:
let view = require('path-to-the-jsx-file');
view = view.default || view;
const ViewElement = React.createFactory(view);
let output = ReactDOMServer.renderToStaticMarkup(ViewElement(props));
它非常适合提供静态 HTML。但是我想知道是否有一种方法可以访问数组或其他东西中 JSX 文件中使用的所有组件,然后我可以使用它来检查绑定(bind)了哪些事件以及哪些处理程序。
所以在这个例子中,可以得到 <h1>
-标签的onClick
-处理程序?这甚至有可能以某种方式做到吗?
最佳答案
为了能够从 onClick 事件中以字符串形式获取函数,我们需要以下内容:
import React from 'React';
export default class Test extends React.Component {
componentDidMount() {
// Gets the name of the function passed inside onClick()
const nameBound = this.element.props.onClick.name;
// Removes 'bound ' from the function name (-> clicked)
const nameString = nameBound.replace('bound ', '');
// Gets the function from the function name as a string
const convertedFunction = this[nameString];
// Converts the function into string
const stringifiedFunction = convertedFunction.toString();
console.log(functionString);
}
clicked() {
alert('Clicked the header!');
}
render() {
return (
<html>
<head>
<title>{this.props.title}</title>
</head>
<body>
<h1 ref={(element) => { this.element = element; }} onClick={this.clicked}>click me!!!</h1>
</body>
</html>
);
}
}
关于javascript - 如何在服务器端 React 中访问 JSX 组件的 DOM 事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46696995/
我是一名优秀的程序员,十分优秀!