Javascript 反应:如何使用onClick添加无限多的组件?

Javascript 反应:如何使用onClick添加无限多的组件?,javascript,reactjs,Javascript,Reactjs,我是新的反应,正在建立一种形式。表单由多个组件组成的集合组成。其中一个组件是textfield 我想创建一个按钮,只需在单击时添加无限量的相同textfield组件。我对如何做到这一点感到困惑,在网上找不到任何信息 到目前为止,我的代码是: constructor(props) { super(props); this.handleClickDestination = this.handleClickDestination.bind(this); } s

我是新的反应,正在建立一种形式。表单由多个组件组成的集合组成。其中一个组件是textfield

我想创建一个按钮,只需在单击时添加无限量的相同textfield组件。我对如何做到这一点感到困惑,在网上找不到任何信息

到目前为止,我的代码是:

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}
    />
)
我想你可以这样做: onClick{this.setState{textFields:[…text};onClick;}

在渲染方法上,可以使用: const TextComponent=this.state.textFields.mapitem=>。 你的部件在这里


你也可以为你的组件设置随机位置。

无限是指真正的无限项吗?比如whiletrue子句,或者简单地说是很多有编号的项?@Prasanna为每个按钮点击一次新组件,所以如果他们点击按钮10次,我希望看到10个新组件。检查答案,让我知道是否有e问题