【问题标题】:Convert Javascript code to ReactJS?将 Javascript 代码转换为 ReactJS?
【发布时间】:2016-04-19 10:23:42
【问题描述】:

我想知道是否可以将一些代码转换成 Javascript 并用 ReactJS 组件编写

有人可以帮帮我吗?

【问题讨论】:

  • Reactjs 是 javascript?!
  • 使用 ReactJS,你可以使用 JSX,它被转译成 javascript。所以你不需要转换你的javascript代码。你可能想阅读一些 ReactJS 文档。
  • 我认为您错误地提出了这个问题。如果我理解正确,您正在寻找将 javascript 代码或函数转换为反应组件或类。

标签: javascript reactjs


【解决方案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;

【讨论】:

    【解决方案2】:

    ReactJS 组件一般都是用 JSX 写的,看起来有点像 XML,不过如果你希望你可以直接用 JS 写。

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 2019-06-28
      • 1970-01-01
      • 2012-03-20
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多