我是React的新手,我已经看过StackOverflow和在线,但是我找不到为什么onClick在这种情况下不起作用的原因。当我单击按钮时,绝对没有任何反应。其他一切都加载。我试过把handleClick放在Button和Buttons中,但是什么也没有。我在App中尝试过构造器/超级,什么也没有。我试过在onClick本身中定义handleClick函数,什么也没有。
应用
class App extends Component {
state = {
randomNumber: RandomNumber,
currentValue: 0,
gameScore: 0,
totalScore: 0,
};
handleClick = event => {
event.preventDefault();
console.log('meow');
}
render() {
return (
<div className="App">
<div className="randomNumber">
<RandomNumber />
</div>
<div className="buttonGrid">
<Buttons onClick={this.handleClick} />
</div>
<div className="currentValue">
Current value = {this.state.currentValue}
</div>
</div>
);
}
}
按钮
class Buttons extends Component {
generateNumber = (min, max) => {
const rndNumBtn = Math.floor(Math.random()*(max-min+1)+min);
console.log(rndNumBtn);
return rndNumBtn
};
state = {
buttons: [
{
id: "black",
src: black,
alt: "blackBtn",
value: this.generateNumber(1, 12)
},
{
id: "brown",
src: brown,
alt: "brownBtn",
value: this.generateNumber(1, 12)
},
{
id: "gray",
src: gray,
alt: "grayBtn",
value: this.generateNumber(1, 12)
},
{
id: "yellow",
src: yellow,
alt: "yellowBtn",
value: this.generateNumber(1, 12)
}
]
};
render() {
return (
<div>
{this.state.buttons.map(button => {
return (
<Button
className={button.id}
key={button.id}
src={button.src}
alt={button.alt}
value={button.value}
/>
)
})}
</div>
)
}
}
按钮
const Button = (props) => {
return (
<button className="zoom">
<img
src={props.src}
alt={props.alt}
value={props.value}
/>
</button>
)
}
答案 0 :(得分:0)
您需要在onClick
上设置<button>
处理程序。 handleClick
在App
中定义,应一路向下传递到<button>
:
...
<Buttons onClick={this.handleClick} />
...
<Button onClick={this.props.onClick} ... />
...
<button className="zoom" onClick={props.onClick}>
答案 1 :(得分:0)
主要问题是Buttons
是一个分组组件,它不呈现可附加事件处理程序的任何DOM元素(输入,按钮等)。如果要在App
中使用事件处理程序,则需要将对它的引用通过组件树向下传递到将要单击的组件-在这种情况下为Button
。
这是一个基于您的代码的示例,向您展示其工作原理。
class App extends React.Component {
constructor () {
super();
this.handleClick = this.handleClick.bind(this);
};
handleClick(event){
console.log(event.target.textContent);
}
render() {
const { buttons } = this.props;
return (
<div className="App">
<Buttons handleClick={this.handleClick} buttons={buttons} />
</div>
)
}
}
function Buttons({ buttons, handleClick }) {
return (
<div>
{buttons.map(button => {
return (
<Button
key={button.id}
handleClick={handleClick}
value={button.value}
/>
)
})}
</div>
)
}
const Button = ({ value, handleClick }) => {
return (
<button
className="zoom"
onClick={handleClick}
>{value}
</button>
)
}
const buttons = [{"id":"black","alt":"blackBtn","value":"1"},{"id":"brown","alt":"brownBtn","value":"2"},{"id":"gray","alt":"grayBtn","value":"3"},{"id":"yellow","alt":"yellowBtn","value":"4"}];
ReactDOM.render(
<App buttons={buttons} />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">