如何在 ReactJS.NET 中使用 React Hooks? [英] How can I use React Hooks with ReactJS.NET?
问题描述
我们目前正在将前端从 jQuery 迁移到 Reactjs.NET.我们使用的是 React 16.8,它允许我们使用 React Hooks 而不是类.
We are currently migrating our frontend from jQuery to Reactjs.NET. We are using React 16.8 which allows us to use React Hooks instead of classes.
我们成功地设置了我们的项目,并首先尝试使用类和服务器端渲染效果很好,但我的团队更喜欢使用 React Hooks.我尝试使用 Webpack + Babel 来转译 .jsx 文件,因为它不再使用剃刀助手 @Html.React()
,但我的组件仍然出现相同的错误.
We setup our project successfully and tried it first with classes and server side rendering which worked well, but my team rather use React Hooks. I tried using Webpack + Babel to transpile .jsx files since it didn't work anymore using only razor helper @Html.React()
, but I still get the same error from my component.
我们使用的是 Asp.NET 4.x 和 NET 框架 4.7.
We are using Asp.NET 4.x and NET framework 4.7.
这是我的观点 children.cshtml
This is my view children.cshtml
@Html.React("ChildrenForm", new {
familyTiesId = Model.FamilyTiesId
},
serverOnly:true
)
这是我的 ReactConfig.cs:
This is my ReactConfig.cs:
namespace Nop.Web
{
public static class ReactConfig
{
public static void Configure()
{
// If you want to use server-side rendering of React components,
// add all the necessary JavaScript files here. This includes
// your components as well as all of their dependencies.
// See http://reactjs.net/ for more information. Example:
ReactSiteConfiguration.Configuration
.AddScript("~/Scripts/Components/Customer/ChildrenForm.jsx");
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
JsEngineSwitcher.Current.EngineFactories.AddV8();
}
}
}
我的组件:
import React, { useState, useEffect } from 'react';
const ChildrenForm = (props) => {
const [ familyTiesId, setFamilyTiesId ] = useState(props.familyTiesId);
...
}
它应该可以工作,但我得到了:
It should work, but instead I get:
SyntaxError: Unexpected identifier
Line 20: @Html.React("ChildrenForm", new {
Line 21: ddtl = Model.DDTL,
Line 22: listFamilies = Model.ListFamilies,
...
[JsCompilationException: SyntaxError: Unexpected identifier
at ChildrenForm.jsx:6:8 -> import React, { useState, useEffect } from 'react';]
JavaScriptEngineSwitcher.V8.V8JsEngine.InnerExecute(String code, String documentName) +258
React.ReactEnvironment.EnsureUserScriptsLoaded() +548
使用 razor helper @Html.React 和服务器端渲染时似乎无法导入文件.
It seems like we cannot import files when using razor helper @Html.React and server side rendering.
如何在服务器端渲染时进行导入和使用 React Hooks?
How can I do an import and use React Hooks while server side rendering?
推荐答案
无需导入,只需使用:
const [ familyTiesId, setFamilyTiesId ] = React.useState(props.familyTiesId);
直接调用 useState
而不是导入.
Just call useState
directly instead of importing.
这篇关于如何在 ReactJS.NET 中使用 React Hooks?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!