如何在组件上调用 setTimeOut class
How to call setTimeOut on a component class
调用 setTimeOut(Question, 3000) 后,我收到错误 "Cannot call a class as a function"。 "Question" 需要是 class 才能获得 classes 接收的生命周期方法。
到目前为止,我找到的唯一答案是在 class 中包含 "extends React.Component",我已经找到了。
import React from 'react';
import Question from './Question';
setTimeout(Question, 3000);
function Congratulations(props) {
return(
<div>
<h1>Congraulations you are the champion.</h1>
<h2>Your Score: {props.score}</h2>
</div>
)
}
export default Congratulations;
接下来是问题组件的前几行 class。
export default class Question extends React.Component {
constructor(props) {
super(props);
我希望问题在 3 秒后出现在 DOM 上。
超时不是你的问题,你只是没有 Reacts 设置代码。查看 React-Dom's render method. 您需要将设置代码包装在一个函数中,然后使用 setTimeout
触发该函数。如果你直接调用它,即使是 React 函数组件也不会做太多事情,就像 setTimeout
会做的那样。
你可以在componentdidmount方法中使用,并在3秒后设置显示状态。在render方法中,只有show为true才能渲染。
在构造方法中,创建一个 show = false 的状态。
在 componentDidMount 你可以创建
setTimeOut(() => this.setState({ show: true}), 3000)
在渲染方法中,您可以使用该状态进行渲染
{
show &&
// render what you want
}
调用 setTimeOut(Question, 3000) 后,我收到错误 "Cannot call a class as a function"。 "Question" 需要是 class 才能获得 classes 接收的生命周期方法。
到目前为止,我找到的唯一答案是在 class 中包含 "extends React.Component",我已经找到了。
import React from 'react';
import Question from './Question';
setTimeout(Question, 3000);
function Congratulations(props) {
return(
<div>
<h1>Congraulations you are the champion.</h1>
<h2>Your Score: {props.score}</h2>
</div>
)
}
export default Congratulations;
接下来是问题组件的前几行 class。
export default class Question extends React.Component {
constructor(props) {
super(props);
我希望问题在 3 秒后出现在 DOM 上。
超时不是你的问题,你只是没有 Reacts 设置代码。查看 React-Dom's render method. 您需要将设置代码包装在一个函数中,然后使用 setTimeout
触发该函数。如果你直接调用它,即使是 React 函数组件也不会做太多事情,就像 setTimeout
会做的那样。
你可以在componentdidmount方法中使用,并在3秒后设置显示状态。在render方法中,只有show为true才能渲染。
在构造方法中,创建一个 show = false 的状态。
在 componentDidMount 你可以创建
setTimeOut(() => this.setState({ show: true}), 3000)
在渲染方法中,您可以使用该状态进行渲染
{
show &&
// render what you want
}