因此,我在一个骰子应用程序上工作,在该应用程序中,我有一个类组件,用于使用向上和向下按钮设置骰子的数量和每个骰子的侧面。我的问题是,每当我按下向上或向下按钮来设置边数或骰子数时,就会创建一个随机数数组并将其显示在屏幕上。但是,我希望仅在单击滚动按钮时显示该值。
所以有一种方法可以在渲染器中创建数组后将displayDice的状态更改为false,以便仅当再次单击“滚动”按钮时它才变为true。
您可以将逻辑移至componentDidMount
。渲染只是渲染UI。没有业务逻辑。它将处理事件并委托给状态。
移动生成随机到父组件,将方法rollChange
从父代传递给子代。
//骰子组件
class SideAndDice extends React.Component {
constructor(props) {
super(props);
this.state = { sides: 6, dice: 1, randoms: this.generateRandom() };
}
increaseDice() {
this.setState({ dice: this.state.dice + 1 });
}
decreaseDice() {
if (this.state.dice > 1) {
this.setState({ dice: this.state.dice - 1 });
}
}
increaseSides() {
this.setState({ sides: this.state.sides + 1 });
}
decreaseSides() {
if (this.state.sides > 2) {
this.setState({ sides: this.state.sides - 1 });
}
}
generateRandom() {
let randoms = [];
for (var i = 0; i < this.state.dice; i++) {
var randomValue = Math.floor(Math.random() * this.state.sides + 1);
randoms.push(randomValue);
}
return randoms;
}
onRollDice() {
this.setState({ randoms: this.generateRandom() });
}
render() {
return (
<div>
<h1>Number of Sides</h1>
<h2>{this.state.sides}</h2>
<button onClick={this.increaseSides.bind(this)}>Up</button>
<button onClick={this.decreaseSides.bind(this)}>Down</button>
<h1>Number of Dice</h1>
<h2>{this.state.dice}</h2>
<button onClick={this.increaseDice.bind(this)}>Up</button>
<button onClick={this.decreaseDice.bind(this)}>Down</button>
<CreateScores
randoms={this.state.randoms}
rollChange={this.rollChange.bind(this)}
/>
</div>
);
}
}
class CreateScores extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onRollDice.bind(this)}>Roll</button>
<br />
<br />
{this.props.randoms.map(random => (
<Dice key={i} diceNumber={randomValue} />
))}
</div>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句