如何在每次加载页面时随机显示一个组件(使用React)?
例如,我有两个组成部分:
<ComponentOne /> and <ComponentTwo />
我想在每个页面加载时随机显示其中一个组件。
我应该在componentDidMount()吗?
class MyComponent extends React.Component {
loadRandomComponent() {
// return <ComponentOne /> || <ComponentTwo />
}
componentDidMount() {
this.loadRandomComponent();
}
}
答案 0 :(得分:4)
看看是否有帮助
class ComponentThree extends React.Component {
render() {
return <div>ComponentThree</div>;
}
}
class ComponentTwo extends React.Component {
render() {
return <div>ComponentTwo</div>;
}
}
class ComponentOne extends React.Component {
render() {
return <div>ComponentOne</div>;
}
}
class Hello extends React.Component {
randomize(myArray) {
return myArray[Math.floor(Math.random() * myArray.length)];
}
render() {
var arr = [<ComponentOne />, <ComponentTwo />, <ComponentThree />]
return <div>Hello {this.randomize(arr)}</div>;
}
}