如何解决无法在反应中有条件地渲染组件
我的 React 应用程序有问题:当某个变量 (repetitions
) 超过阈值时,我需要有条件地在屏幕上呈现一个按钮。
该变量被更新到 componentDidMount()
函数中,该函数从网络摄像头检索视频并根据它在视频中检索的内容更新上述变量:
export default class Recognizer extends Component {
constructor(props) {
super(props);
this.state = {
repetitions : 0,max_repetitions : 15
};
}
componentDidMount(){
const videoElement = document.getElementsByClassName('input_video')[0];
const canvasElement = document.getElementsByClassName('output_canvas')[0];
const canvasCtx = canvasElement.getContext('2d');
function onResults(results) {
canvasCtx.save();
canvasCtx.clearRect(0,canvasElement.width,canvasElement.height);
canvasCtx.drawImage(results.image,canvasElement.height);
var point;
var sample = [];
for (point = 0; point < results.poseLandmarks.length; point++) {
sample.push(results.poseLandmarks[point].x*canvasElement.width)
sample.push(results.poseLandmarks[point].y*canvasElement.width)
sample.push(results.poseLandmarks[point].z*canvasElement.width)
}
let result=predict(sample) //some kind on ML in "predict" function
if (result==1) {
repetitions=repetitions+1 // <-- I should update this.state.repetitions here but I cannot access "this"
}
canvasCtx.restore();
}
const pose = new Pose({locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/pose@0.3.1620325689/${file}`;
}});
pose.onResults(onResults);
const camera = new Camera(videoElement,{
onFrame: async () => {
await pose.send({image: videoElement});
},width: 1280,height: 720
});
camera.start();
}
render() {
return (
<div className="Home">
<div className="lander">
<div className="App">
<video hidden className="input_video"></video>
<canvas className="output_canvas" width="1280px" height="720px"></canvas>
</div>
{this.state.repetitions > this.state.max_repetitions ? <form><Button className="btn-action">Continue</Button></form>: null }
</div>
</div>
);
}
}
正如您在代码中看到的,有一个 onResults
函数到 componentDidMount()
中有没有办法从那里访问状态变量?
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。