将 Javascript 代码转换为 ReactJS?

新手上路,请多包涵

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

有人能帮助我吗 ?

原文由 Randa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 284
1 个回答

较旧的方式

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

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

 // 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;


原文由 alanionita 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题