你好,我是React js的新手。我们必须创建一个项目来计算团队的积分,共有4个团队。每个小组有5个孩子。现在,我创建了一个ID为5的数组。 5个柜台是为孩子们准备的。您应该能够为每个孩子添加积分。因此,可以使用按钮通过id更新它。我在laravel中使用React。这是代码:
export default class Gryffindor extends Component {
constructor(props) {
super(props);
this.state = {
counters: []
};
this.fetchCounter = this.fetchCounter.bind(this);
}
fetchCounter(e) {
const counters = [
{ id: 1, amount: 0 },
{ id: 2, amount: 0 },
{ id: 3, amount: 0 },
{ id: 4, amount: 0 },
{ id: 5, amount: 0 }
];
this.setState({ counters });
}
render() {
return <CounterBody counters={this.state.counters} />;
}
}
const CounterBody = ({ counters }) => (
<table>
<thead>
<tr>
<th>Test</th>
<th>Test</th>
<th>Test</th>
</tr>
</thead>
<tbody>
{counters.map(counter => (
<tr key={counter.id}>
<td></td>
<td>{counter.amount}</td>
<td></td>
</tr>
))}
</tbody>
</table>
);
if (document.getElementById("Gryffindor")) {
ReactDOM.render(<Gryffindor />, document.getElementById("Gryffindor"));
}
我不知道为什么它没有出现。有人可以帮我吗?
答案 0 :(得分:0)
您永远不会呼叫fetchCounter
。您可以在componentDidMount
内部调用它。
class Gryffindor extends React.Component {
constructor(props) {
super(props);
this.state = {
counters: []
};
this.fetchCounter = this.fetchCounter.bind(this);
}
componentDidMount() {
this.fetchCounter();
}
fetchCounter() {
const counters = [
{ id: 1, amount: 0 },
{ id: 2, amount: 0 },
{ id: 3, amount: 0 },
{ id: 4, amount: 0 },
{ id: 5, amount: 0 }
];
this.setState({ counters });
}
render() {
return <CounterBody counters={this.state.counters} />;
}
}
const CounterBody = ({ counters }) => (
<table>
<thead>
<tr>
<th>Test</th>
<th>Test</th>
<th>Test</th>
</tr>
</thead>
<tbody>
{counters.map(counter => (
<tr key={counter.id}>
<td />
<td>{counter.amount}</td>
<td />
</tr>
))}
</tbody>
</table>
);
ReactDOM.render(<Gryffindor />, 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"></div>