我需要知道是否可能将一些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;
现代的模式是不再像上面那样拥有容器组件。
这个逻辑现在将会存在于一个hook里,并且会使用状态hooks来存储数据。
// 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代码。
function addHyphen (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.match(/.{1,3}/g).join('-');
document.getElementById(element.id).value = finalVal;