我想在按钮被按下时动态地添加这个卡片组件。所以,如果我按了3次按钮,3张卡必须被添加到DOM中。谁能帮我解决一下为什么不能用,我是新来的react.thanks in advance. 是不是因为我不能在render方法之外使用component
import React, {Component} from 'react';
import Card from './Card'
class App extends Component {
addRobotHandler = () => {
return (
<Card/>
)
}
render() {
return (
<div>
<button onClick={this.addRobotHandler}>Click me to see Robots</button>
</div>
);
}
}
export default App;
你可以添加一个定义计数的状态,并在你的渲染函数中渲染该数量的卡。
// sample example
class Example extends Component {
constructor(props) {
super(props);
this.state = {
cardsCount: 0
};
}
addRobotHandler = () => {
this.setState(prevState => {
return { cardsCount: prevState.cardsCount + 1 };
});
};
getCards = () => {
let cards = [];
for(let i = 0; i < this.state.cardsCount; i++) {
cards.push(<Cards/>)
}
return cards;
}
render() {
return (
<div>
<button onClick={this.addRobotHandler}>Click me to see Robots</button>
{this.getCards()}
</div>
);
}
}