gpt4 book ai didi

javascript - react : How to add an infinite an infinite amount of components with onClick?

转载 作者:行者123 更新时间:2023-12-03 00:33:08 25 4
gpt4 key购买 nike

我是 React 新手,正在构建一个表单。该表单由多个组件组成的集合组成。组件之一是文本字段。

我想创建一个按钮,只需单击即可添加无限数量的相同文本字段组件。我对如何执行此操作感到困惑,并且在网上找不到任何信息。

到目前为止我的代码是:

constructor(props) {
super(props);
this.handleClickDestination = this.handleClickDestination.bind(this);
}

static defaultProps = {
}

static propTypes = {
}

handleClickDestination() {
console.log('click');
}

render() {

const {
className
} = this.props;

return (
<div className={className}>
<DestinationSearchInput />
<Grid item margin="normal">
</Grid>
<Grid container spacing={12} alignItems="flex-end">
<Button onClick={this.handleClickDestination} color="primary">
Add another destination
</Button>
</Grid>
<div>
// extra <DestinationSearchInput /> components to go here
</div>
<DatePicker />
<TravellerCounter />
</div>
);
}
}

有人能指出我如何实现这一目标的正确方向吗?

最佳答案

您可以使用状态让组件知道要呈现多少个目标字段

在本例中,我只是使用了一组虚拟项来多次渲染字段。

constructor() {
this.state = {
items: ['dummy']
}
}
handleClickDestination() {
this.setState({items: this.state.items.concat('dummy') })
}

render() {

const {
className
} = this.props;

return (
<div className={className}>
<DestinationSearchInput />
<Grid item margin="normal">
</Grid>
<Grid container spacing={12} alignItems="flex-end">
<Button onClick={this.handleClickDestination} color="primary">
Add another destination
</Button>
</Grid>
<div>
// use this block here
{
this.state.items.map((_, index) =>
<DestinationSearchInput
key={index}
/>
)
}
// use this block here
</div>
<DatePicker />
<TravellerCounter />
</div>
);
}

或者简单地使用一个数字,然后使用它进行渲染

// in constructor
this.state = {items: 0}

// inside handle click
this.setState({items: this.state.items + 1})

// in render
new Array(this.state.items).fill(0).map((_,index) =>
<DestinationSearchInput
key={index}
/>
)

关于javascript - react : How to add an infinite an infinite amount of components with onClick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53773757/

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