gpt4 book ai didi

javascript - 使用 React 从 HTML 文件调用 .js 文件中的 Javascript 函数

转载 作者:行者123 更新时间:2023-11-30 15:33:52 30 4
gpt4 key购买 nike

我还没有找到这个具体问题,所以这里是:

假设我有一个 HTML 文件。在这个 HTML 文件中,我在 body 元素中有一些 React 类和函数。一个功能是呈现表单。例如:

renderForm: function() {
return (
<div className="form_div">
Movie search: <input type="text" className="query"></input>
<button onClick={this.search} className="submit">Search</button>
</div>
);
},

现在。我还有一个 .js 文件。在这个文件中,我有一个完成的函数“搜索”来处理用户输入并传递给数据库/API/我想搜索的内容。这是一个相当大的函数。

我可以使用我的 HTML 文件中的 React 代码调用此 .js 文件中的搜索功能吗?

目标是用 React 处理渲染,用 JS 处理功能。

这可能吗(我不是问这是否是好的做法)?

最佳答案

是的,只需确保将该函数附加到您的 React 组件(这样您就可以通过 this 访问它)或直接使用该函数(search 而不是 this.search) 如果你打算让它保持全局(或者可能从 module 导入)。

我会说将它用作外部函数更容易:

renderForm: function() {
return (
<div className="form_div">
Movie search: <input type="text" className="query"></input>
<button onClick={search} className="submit">Search</button>
</div> /* ^------ search comes from a script that's loaded before this code so we can just call it */
);
}

如果 search 中的逻辑更通用或与您正在创建的组件无关,这也是一种更好的方法,因为它将为您提供 looser coupling .


如果搜索依赖于特定组件(需要 this 绑定(bind)),您需要将其附加到您的 React 组件。实际语法取决于您是否使用 ES6 classesReact.createClass .

使用类的一种方法是围绕全局搜索创建一个包装器方法,该方法将在适当的上下文中调用它:

class MyComponent extends React.Component {
constructor() {
// ...
}

search(...args) {
search.apply(this, ...args); // <--- Call the global search but bind `this` to the React component instance.
}

// now you can use this.search in renderForm
renderForm() { ... }
}

您还可以将 search 直接附加到 prototype你的组件而不是使包装函数:

class MyComponent extends React.Component {
// ...

// you can use this.search in renderForm because it will be found on the prototype
renderForm() { ... }
}

MyComponent.prototype.search = search; // <-- attach global search to the prototype of your component

就使用 React.createClass 而言,您只需将对全局 search 的引用附加到您传入的对象。任何作为方法调用的函数对象自动将 this 设置为该对象:

var MyComponent = React.createClass({

search: search, // <-- attach global search to your component,

// now you can use this.search in renderForm because it is a method of your component
renderForm() { ... }
});

关于javascript - 使用 React 从 HTML 文件调用 .js 文件中的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41875918/

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