所以我正在开发一个骰子应用程序,其中有一个类组件,用于通过向上和向下按钮设置骰子的数量和每个骰子的边数。我的问题是,每次我按向上或向下按钮设置面数或骰子数量时,都会创建一组随机数并显示在屏幕上。但是,我希望仅在单击滚动按钮时显示该值。
那么有没有一种方法可以在渲染中创建数组后将 displayDice 的状态更改为 false,这样只有当我再次单击滚动按钮时它才变为 true
最佳答案
您可以将逻辑移动到componentDidMount
。渲染只是渲染UI。没有业务逻辑。它将处理事件并委托(delegate)给状态。
将生成随机数移至父组件,将方法 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>
);
}
}
关于javascript - 有什么方法可以改变 React js 中渲染的状态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60903675/