gpt4 book ai didi

javascript - 如何在服务器端 React 中访问 JSX 组件的 DOM 事件处理程序

转载 作者:IT老高 更新时间:2023-10-28 23:21:36 24 4
gpt4 key购买 nike

我正在使用 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 事件中以字符串形式获取函数,我们需要以下内容:

  1. 元素的 DOM
    • 我们可以通过附上 ref我们的 h1 元素上的属性
  2. 传递给 onClick 事件(点击)的函数的名称
  3. 函数本身来自一个包含函数名的字符串
    • 由于我们在 React 组件中方便地使用方法,我们可以在组件中使用 this['functionName'] 来获取函数。
  4. 函数的字符串化版本

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com