React로 만든 페이지에 업데이트 시계를 추가하고 싶습니다. 다음은 원본 CodePen 데모입니다. 시계를 구동하는 자바 스크립트를 통합하는 방법을 잘 모르겠습니다. FunctionalComponents를 사용하고 있습니다. 자바 스크립트 코드는 어디에 넣습니까?
내 기존 앱 (에 시계 HTML이 추가됨 .clockDiv
) :
import { h, FunctionalComponent } from 'preact';
import style from './company.scss';
import Markup from 'preact-markup';
import Typography from '@material-ui/core/Typography';
import { useEffect, useState, useContext } from 'preact/hooks';
import { get } from '../../utils/ajax';
import { SvgMap } from './Components/SvgMap';
import { AppContext, CMSContent } from '../../store/store';
export const Company: FunctionalComponent = () => {
const { language: lang } = useContext(AppContext);
const [pageContent, setpageContent] = useState<string | undefined>(undefined);
/* *********************************************************************** */
useEffect(() => {
const companyTab = 'Company';
const editCompany = 'locUSA';
get<CMSContent[]>(`/getPageHTML?tab=${companyTab}&company=${editCompany}&lang=${lang}`).then((companyContent) => {
setpageContent(companyContent[0].html);
});
}, [lang]);
/* *********************************************************************** */
return (
<div class={style.companyDiv}>
<div class={style.pageData}>
{pageContent !== undefined && (
<Typography>
<div class={style.topStuff}>
<div class={style.pageContent}>
<Markup markup={pageContent} trim={false} type='html' />
</div>
<div class={style.clockDiv}>
<div class={style.timedate}>
<a id="mon">January</a>
<a id="d">1</a>,
<a id="y">0</a><br />
<a id="h">12</a> :
<a id="m">00</a>:
<a id="s">00</a>:
<a id="mi">000</a>
</div>
</div>
</div>
</Typography>
)}
</div>
</div>
);
};
export default Company;
시계를 움직이는 자바 스크립트는 다음과 같습니다.
Number.prototype.pad = function(n) {
for (let r = this.toString(); r.length < n; r = 0 + r);
return r;
};
function updateClock() {
const now = new Date();
const milli = now.getMilliseconds();
const sec = now.getSeconds();
const min = now.getMinutes();
const hou = now.getHours();
const mo = now.getMonth();
const dy = now.getDate();
const yr = now.getFullYear();
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const tags = ["mon", "d", "y", "h", "m", "s", "mi"];
const corr = [months[mo], dy, yr, hou.pad(2), min.pad(2), sec.pad(2), milli];
for (let i = 0; i < tags.length; i++)
document.getElementById(tags[i]).firstChild.nodeValue = corr[i];
}
function initClock() {
updateClock();
window.setInterval("updateClock()", 1);
}
일반 자바 스크립트 위젯을 React 앱에 통합하는 방법을 살펴본 것은 이번이 처음입니다. 매우 간단한 페이지에 추가되는 매우 간단한 위젯이므로 합리적으로 간단해야하지만 TBH 어디서부터 시작해야할지 모르겠습니다.
누구든지 올바른 방향으로 나를 가리킬 수 있습니까? 아마도 이런 종류의 하우투가 있습니까?
PS-Preact는 React와 거의 동일하며 모든 Reactic 솔루션이 작동합니다.
JS 코드를 updateClock
함수 를 내보내는 별도의 파일로 저장 하거나 Company
구성 요소 파일 내에서 정의 할 수 있습니다 .
그런 다음 다른 함수 useEffect
를 추가 하여 updateClock
함수 를 호출 하고 원래 initClock
함수 를 바꿉니다 .
이 같은:
// Import or define the updateClock function...
import { updateClock } from './utils/clock';
// Within your component...
useEffect(() => {
updateClock();
const interval = window.setInterval(updateClock, 1);
// Clear the interval if/when the component is removed from the DOM
return () => window.clearInterval(interval);
}, []);
참고 : 테스트되지 않은 코드는 조정이 필요할 수 있습니다 ...
물론 이것은 실제로 이것을 수행하는 반응 방식은 아니지만 더 반응하도록 함수를 다시 작성할 시간이 없습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다