gpt4 book ai didi

javascript - 使用 React.js 的随机数

转载 作者:数据小太阳 更新时间:2023-10-29 04:01:21 27 4
gpt4 key购买 nike

我写了这段代码,但是当我运行它时,我只得到一个空白页面。怎么了?看来我已经接近答案了。我已经尝试了所有方法,但仍然无法正常工作。

class Button extends React.Component {

constructor(props) {
super(props);
this.state = {
random: 0
}
}


render() {
var min = 1;
var max = 100;
var rand = min + (Math.random() * (max-min));
handleClick() {
this.setState ({this.state.random + this.rand})
}
return (
<div>
<button value="Click me!" onClick={this.handleClick.bind(this)></button>
</div>
);

React.render(<Button />, document.querySelector('#container'));

}
}

JSFIDLLE:https://jsfiddle.net/1cban4oy/12/

最佳答案

从渲染函数中移除所有逻辑并将其添加到点击处理程序方法中。此外,onClick 末尾缺少大括号。最后,您没有在 setState() 方法中指明要更新的状态属性。

这基本上似乎可以满足您的要求: https://codesandbox.io/s/98n9EkEOJ

这是以防万一的代码:

import React from 'react';
import { render } from 'react-dom';

class Button extends React.Component {

constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = { random: 0 };
}

handleClick() {
const min = 1;
const max = 100;
const rand = min + Math.random() * (max - min);
this.setState({ random: this.state.random + rand });
}

render() {
return (
<div>
<button onClick={this.handleClick.bind(this)}>Click</button>
<div>The number is: {this.state.random}</div>
</div>
);
}
}

render(<Button />, document.getElementById('container'));

关于javascript - 使用 React.js 的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45175836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com