将Javascript代码转换为ReactJS

Convert Javascript code to ReactJS?

本文关键字:ReactJS 转换 代码 Javascript      更新时间:2023-09-26

我需要知道是否可以转换一些代码Javascript并使用ReactJS组件编写

有人能帮帮我吗?

较旧的方式

如果你的功能只是后端代码或脚本,你可以创建一个传递组件或容器组件

该组件只执行脚本,然后呈现另一个组件,通常是视觉组件或表示组件。

// React container component
import React from 'react';
import ViewComponent from './ViewComponent'
function thisIsPlainJs () {
   // get me some data from apiUrl
   const data = fetch(apiUrl)
   return data;
}
const Container = () => {
   // this calls the function and gets the result
   const someData = thisIsPlainJs();
   // the result can then be passed on to the view component
   // <ViewComponent/> doesn't have any logic just use the data to render html
   return <ViewComponent data={...someData}/>
}
export default Container;
// React view/presentational component
import React from 'react';
const ViewComponent = (props) => (
   <p>{props.data.text}</p>
)
export default ViewComponent;

更新的方式

现代模式是没有像上面那样的容器组件。

该逻辑现在将存在于钩子中,并将使用状态钩子来存储数据。

// React hook
import { useState, useEffect } from 'react';
export function useThisIsPlainJs() {  
  const [data, setData] = useState(null);
  useEffect(() => {
     const dataRes = fetch(apiUrl);
     dataRes && setData(dataRes);
  });
  return data;
}
// React view/presentational component
// - because we don't need a container component this here is NextComponent from above
import React from 'react';
import { useThisIsPlainJs } from './hooks'
const ViewComponent = () => (
   // this calls the hook and gets the data
   // if you noticed we don't need props because we assume that this comp if top of the tree
   const { data } = useThisIsPlainJs();
   // we render the data directly if it exists
   return <p>{data && data.text}</p>
}
export default ViewComponent;

ReactJS组件通常是用JSX编写的,它看起来有点像XML,但如果您希望可以直接用JS编写。

如果你想了解更多关于JSX的信息,请阅读此处https://facebook.github.io/react/docs/jsx-in-depth.html

在你的构建过程中,你可以集成Babel(它与Gulp、Grunt、Webpack等工具一起工作),这将允许你将你的JSX编译成JS,你也可以继续使用Babel来转换ES2015/ES6代码。

PD_6