似乎无法使此onClick
按钮正常工作并更新“给定的荣誉”编号。基本上是3个.js文件,同时使用this API进行测试。我的代码是:
app.js:
import React, { Component } from 'react';
import './App.css';
import KudoList from "./components/KudoList";
import axios from "axios";
class App extends Component {
state = {
contacts: []
};
componentDidMount() {
axios
.get("https://kudos-devtech8-yvbvpoek.herokuapp.com/users")
.then(response => {
const newContacts = response.data.map(c => {
return {
id: c.id,
name: c.username,
fname: c.first_name,
lname: c.last_name,
kgive: c.kudos_given_count,
kreceived: c.kudos_received_count
};
});
const newState = Object.assign({}, this.state, {
contacts: newContacts
});
this.setState(newState);
})
.catch(error => console.log(error));
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to our Kudo app</h1>
</header>
<KudoList contacts={this.state.contacts} />
</div>
);
}
}
export default App;
Contact.js:
import React from "react";
import "./Contact.css";
class Contact extends React.Component {
state = { kgive: 0,
fname: '',
lname: '',
kreceived: ''
};
constructor(props) {
super(props);
this.incrementKudoCount = this.incrementKudoCount.bind(this);
}
incrementKudoCount(ev) {
this.setState((prevState) => ({
kgive: prevState.kgive+ 1,
}));
}
render() {
return (
<div className="appPerson">
<p>Name: {this.props.fname} {this.props.lname} <button onClick={() => this.incrementKudoCount()}>Give Kudo!</button></p>
<p>Kudos Given: {this.props.kgive}</p>
<p>Kudos Received: {this.props.kreceived}</p>
</div>
);
}
}
export default Contact;
然后是KudoList.js:
import React from "react";
import Contact from "./Contact";
function KudoList(props) {
return (
<div>
{props.contacts.map(c => <Contact key={c.id} name={c.name} fname={c.fname} lname={c.lname} kgive={c.kgive} kreceived={c.kreceived} /> )}
</div>
);
}
export default KudoList;
我没有收到任何错误,但是按钮绑定事件无法正常工作,并且不确定原因。我应该有一个单独的组件来提供工藤吗,还是不能像我稍加修改就变得一样容易?
答案 0 :(得分:1)
事件侦听器应该是一个函数。我看到您正在返回(调用)该函数。
只是onClick={this. incrementKudoCount}
应该起作用。
** UPDATE:可运行的沙箱**(由于stackoverflow沙箱不支持导入) https://codesandbox.io/embed/j2w729p329