将 HTML 转换为 ReactJS 组件
Posted
技术标签:
【中文标题】将 HTML 转换为 ReactJS 组件【英文标题】:Converting HTML to ReactJS Components 【发布时间】:2021-09-27 11:44:27 【问题描述】:我正在做这个练习来全面了解如何在 Reactjs 中将 html 转换为组件,但它产生了错误。担心我在组件中放错了一些反应元素。谁能给我一个要点,说明从 HTML 到我的 react javascript 组件的去向。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Audio File Loader</title>
<meta name="description" content="A way to make sure files have loaded before playing them">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!--
Some browsers' autoplay policy requires that an AudioContext be initialized
during an input event in order to correctly synchronize.
So provide a simple button to get things started.
-->
<button id="startbutton">Press to load tracks</button>
<div class="wrapper">
<section id="tracks">
<ul>
<li data-loading="true">
<a href="leadguitar.mp3" class="track">Lead Guitar</a>
<p class="loading-text">Loading...</p>
<button data-playing="false" aria-decribedby="guitar-play-label" class="playbutton">
<span id="guitar-play-label">Play</span>
</button>
</li>
<li data-loading="true">
<a href="bassguitar.mp3" class="track">Bass Guitar</a>
<p class="loading-text">Loading...</p>
<button data-playing="false" aria-describedby="bass-play-label" class="playbutton">
<span id="bass-play-label">Play</span>
</button>
</li>
<li data-loading="true">
<a href="drums.mp3" class="track">Drums</a>
<p class="loading-text">Loading...</p>
<button data-playing="false" aria-describedby="drums-play-label" class="playbutton">
<span id="drums-play-label">Play</span>
</button>
</li>
<li data-loading="true">
<a href="horns.mp3" class="track">Horns</a>
<p class="loading-text">Loading...</p>
<button data-playing="false" aria-describedby="horns-play-label" class="playbutton">
<span id="horns-play-label">Play</span>
</button>
</li>
<li data-loading="true">
<a href="clav.mp3" class="track">Clavi</a>
<p class="loading-text">Loading...</p>
<button data-playing="false" aria-describedby="clavi-play-label" class="playbutton">
<span id="clavi-play-label">Play</span>
</button>
</li>
</ul>
<p class="sourced">All tracks sourced from <a href="http://jplayer.org/">jplayer.org</a></p>
</section>
</div><!-- wrapper -->
<script type="text/javascript">
console.clear();
// for cross browser compatibility
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioCtx = null;
// Provide a start button so demo can load tracks from an event handler for cross-browser compatibility
const startButton = document.querySelector('#startbutton');
console.log(startButton);
// select all list elements
const trackEls = document.querySelectorAll('li');
console.log(trackEls);
// switch aria attribute on click
// allPadButtons.forEach(el =>
// el.addEventListener('click', () =>
// if (el.getAttribute('aria-checked') === 'false')
// el.setAttribute('aria-checked', 'true');
// else
// el.setAttribute('aria-checked', 'false');
//
// , false)
// )
// Loading ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// function for fetching the audio file and decode the data
async function getFile(filepath)
const response = await fetch(filepath);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
return audioBuffer;
// function to call each file and return an array of decoded files
async function loadFile(filePath)
const track = await getFile(filePath);
return track;
let offset = 0;
// create a buffer, plop in data, connect and play -> modify graph here if required
function playTrack(audioBuffer)
const trackSource = audioCtx.createBufferSource();
trackSource.buffer = audioBuffer;
trackSource.connect(audioCtx.destination)
if (offset == 0)
trackSource.start();
offset = audioCtx.currentTime;
else
trackSource.start(0, audioCtx.currentTime - offset);
return trackSource;
startButton.addEventListener('click', () =>
if (audioCtx != null)
return;
audioCtx = new AudioContext();
document.querySelector("#startbutton").hidden = true;
trackEls.forEach((el, i) =>
// get children
const anchor = el.querySelector('a');
const loadText = el.querySelector('p');
const playButton = el.querySelector('.playbutton');
// load file
loadFile(anchor.href).then((track) =>
// set loading to false
el.dataset.loading = 'false';
// hide loading text
loadText.style.display = 'none';
// show button
playButton.style.display = 'inline-block';
// allow play on click
playButton.addEventListener('click', function()
// check if context is in suspended state (autoplay policy)
if (audioCtx.state === 'suspended')
audioCtx.resume();
playTrack(track);
playButton.dataset.playing = true;
)
)
)
);
</script>
</body>
</html>
【问题讨论】:
【参考方案1】:大意是这样的;
您创建一个反应组件,并且;
您将 html 中的所有内容放在 react 组件的 renders 返回方法中。不要忘记将类名更改为类名。
您将 CSS 放在一个 .css 文件中,并将其与组件一起导入到您的 jsx 文件的顶部。
任何 javascript 都可以放在你的组件中,在 render 方法之前。您将需要阅读钩子和状态以利用反应的力量。否则,您放入的所有 js 都会在每次渲染时天真地运行。
head 标签包括标题和网站图标之类的内容,您希望将它们放置在您的 react 应用程序的 public/index.js 文件中。
如果您有任何问题,请告诉我 :-)
【讨论】:
谢谢,知道了! :) 读了几遍。仍然感到困惑:1)何时将某些html部分置于状态; 2) 哪个部分进入componentDid/Will 1) 永远不要将 HTML 置于某种状态。如果您想使用状态操作 html,请使用 JSX。有关更多信息,请参阅 React 文档入门。他们有关于状态和生命周期钩子(didMount 等)的练习。 2)不要使用组件 - 使用功能反应。然后它将是一个useEffect。如果您确实使用了组件,则 componentDid 将在事件之后触发,而 componentWill 将在应用事件之前触发。 didMount 就像是加载该特定组件。以上是关于将 HTML 转换为 ReactJS 组件的主要内容,如果未能解决你的问题,请参考以下文章
ReactJs - 将带有嵌套 React 组件的原始 HTML 转换为 JSX