我正在尝试创建一个单页React应用程序,该应用程序一次安装某些组件。组件全部一次加载。
我发现有关安装组件的StackOverflow帖子是关于防止它们在更改时重新呈现。我有3个部分,我只希望其中一个出现在页面加载中。我希望计时器首先出现。当按下开始按钮时,我希望出现问题。最后,当计时器为零或用户按下提交按钮时,将显示结果。各个组件都可以按我的意愿工作,但是我想隐藏它们直到被调用。仅供参考-(selectedOption)来自React-Select依赖项。
回购:https://github.com/irene-rojas/pixar-react
应用
import React, { Component } from 'react';
import './App.css';
import Timer from "./Timer";
import Questions from "./Questions/Questions.js";
import Results from "../src/Results";
class App extends Component {
state = {
totalTrue: 0,
totalFalse: 0,
}
componentDidMount() {
return (
<Timer />
)
}
// submit button
handleFormSubmit = event => {
event.preventDefault();
console.log("submit button clicked");
return (
<Results />
)
};
callbackHandlerFunction = ( selectedOption ) => {
const answerValue = selectedOption.value;
if (answerValue === true) {
this.setState({totalTrue: this.state.totalTrue + 1}, () => {
console.log(`New TotalTrue: ${this.state.totalTrue}`);
});
};
if (answerValue === false) {
this.setState({totalFalse: this.state.totalFalse + 1}, () => {
console.log(`New TotalFalse: ${this.state.totalFalse}`);
});
};
}
render() {
return (
<div className="parallax">
<div className="App">
<div className="wrapper">
<div className="headerDiv">
<h1>Pixar Trivia!</h1>
</div>
<div className="timerDiv">
<Timer />
</div>
<div className="questionSection">
<Questions
handleClickInParent={this.callbackHandlerFunction}
/>
<div>
<button onClick={this.handleFormSubmit}>Submit</button>
</div>
</div>
{/* this code will hide Results until these conditions are met. This was an experiment to see if anything hid Results from mounting on load */}
{this.state.totalTrue >= 8 && this.state.totalFalse >= 8 &&
<div className="resultsDiv">
<Results
totalTrue={this.state.totalTrue}
totalFalse={this.state.totalFalse}
/>
</div>
}
</div>
</div>
</div>
);
}
}
export default App;
计时器
import React, { Component } from 'react';
class Timer extends Component {
state = {
timer: 10
};
startTimer = () => {
this.timer = setInterval(() => this.setState({
timer: this.state.timer - 1}), 1000);
// onClick, load Questions
// but do I need to import Questions?
};
stopTimer = () => {
clearInterval(this.timer);
alert("Time's up!");
// when this.state.timer === 0, load Results
// do I need to import Results?
};
render() {
return (
<div className="Timer">
<div>{this.state.timer} seconds</div>
<button onClick={this.startTimer}>Start!</button>
{this.state.timer === 0 && this.stopTimer()}
</div>
);
}
}
export default Timer;
答案 0 :(得分:3)
您应该查看conditional rendering。默认情况下,您应用的render()
包含所有子组件。您要么要将它们设置为隐藏,要么根本不渲染它们。
例如
{conditionToMeet &&
<div>
content to render here
</div>
}
答案 1 :(得分:0)
您可以在render
方法内检查条件并显示所需的组件
render() {
let renderedContent;
if (condition to meet) {
renderedContent = <Component1>
} else if ( second condition to meet) {
renderedContent = <Component2>
} else {
renderedContent = <Component3>
}
return (
{ renderedContent }
)
}