[英]How to make OnLoad Event work for React Widget?
在用 react 创建组件后,我试图调用 function 一次。我是新手,所以希望你能帮助我理解。 我尝试将 onLoad 事件放在组件创建中,但它不起作用。 我试图只拨打 function 电话,但它在圈子中被调用,但我需要它被调用一次 - 当组件完成加载时。
下面是我必须创建组件的 function,我希望在加载组件时也调用 function 'handleClick'。
function BadgeSample(props) {
const {
type,
defaultValue,
className,
style,
value,
bootstrapStyle,
clickable,
onClickAction,
getRef
} = props;
const [disabled, setDisabled] = React.useState(false);
const [pasuedd, setPasued] = React.useState(false);
const [highlightSection, setHighlightSection] = React.useState({
from: 0,
to: 0
});
const synth = window.speechSynthesis;
let utterance;
const handleClick = () => {
if (!synth) {
console.error("no tts");
return;
}
utterance = new SpeechSynthesisUtterance(value || defaultValue);
utterance.addEventListener("start", () => setDisabled(true));
utterance.addEventListener("end", () => setDisabled(false));
utterance.addEventListener("boundary", ({
charIndex,
charLength
}) => {
setHighlightSection({
from: charIndex,
to: charIndex + charLength
});
});
synth.speak(utterance);
};
const stoped = () => {
synth.cancel(utterance);
};
const pasued = () => {
setPasued(true);
synth.pause(utterance);
};
const resumed = () => {
setPasued(false);
synth.resume(utterance);
};
//handleClick(); - here it will work, but it will repeat itself in the loop and never stopped
return React.createElement("div", {
className: "App",
onClick: onClickAction,
onLoad: handleClick, // - here it doesn't work..
ref: getRef,
style: style
}, React.createElement(HighlightedText, _extends$sj({
text: value || defaultValue
}, highlightSection)), React.createElement("button", {
className: disabled ? "stopbtn" : "playbtn",
onClick: disabled ? stoped : handleClick
}, disabled ? React.createElement("div", null, React.createElement(StopCircleFill, null), "Stop") : React.createElement("div", null, React.createElement(PlayCircleFill, null), "Listen")), disabled ? React.createElement("button", {
className: pasuedd ? "playbtn" : "pausebtn",
onClick: pasuedd ? resumed : pasued
}, pasuedd ? React.createElement("div", null, React.createElement(PlayCircleFill, null), "Resume") : React.createElement("div", null, React.createElement(PauseCircleFill, null), "Pause")) : "");
}
我尝试在加载带有组件的页面后调用 function .. 但它不起作用。
你可以使用使用效果。 这是我所知道的最高效的方式,而且使用起来非常舒适。 它是一个 function,您可以决定何时调用它,并且您可以选择在您的网站第一次呈现时只调用一次。
这是一个例子:
import React, { useEffect } from 'react';
const YourComponent = () => {
useEffect(() => {
// your function here
}, []);
return (
// your component's content and so... );
};
如果您希望在其中一个状态发生变化时调用它,您也可以这样做。 我强烈建议您阅读它并将其用于您的项目。 希望能帮助到你:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.