代码之家  ›  专栏  ›  技术社区  ›  MeltingDog

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

  •  0
  • MeltingDog  · 技术社区  · 7 年前

    我是新的反应,正在建立一种形式。表单由多个组件组成的集合组成。其中一个组件是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>
            );
        }
    }
    

    2 回复  |  直到 7 年前
        1
  •  1
  •   Prasanna    7 年前

    在本例中,我刚刚使用了 dummy 要多次渲染字段的项。

    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}
        />
    )
    
        2
  •  0
  •   Tony Bui    7 年前

    我想你可以这样做: onClick(){this.setState({textFields:[…text});onClick();}

    在渲染方法上,可以使用: const TextComponent=this.state.textFields.map(item=>)。
    (此处为您的组件)

    您也可以为组件放置随机位置。