将Javascript代码转换为ReactJS
Convert Javascript code to ReactJS?
我需要知道是否可以转换一些代码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
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- 如何在Javascript中将JSon对象转换为数组
- 使用JS将数组转换为json对象
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- 如何使用json将对象列表从java转换为javascript
- 偶尔结结巴巴地说“;堆叠的”;translate()上的转换(v4.0.0-alpha40)
- 为什么在单独的函数中应用时转换会闪烁/断断续续(D3)
- 在Javascript中转换对象数组
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 将数字转换为一定数量的硬币
- 将纯文本URL转换为可单击链接
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 如何使用js将SNAPSHOT内部版本号转换为3位数的整数
- 如何更改reactjs中外部/独立组件的状态或属性
- 如何将TypeScript对象转换为普通对象
- 将Javascript代码转换为ReactJS
- 旧的LeftNav菜单样式和Reactjs的可组合菜单样式之间的材质ui转换
- 如何将jQuery removeClass转换为ReactJS方式
- 将内容从html转换为ReactJS文件