React-基于计数的动态输入字段

 收藏

我想根据用户输入的计数创建文本字段。我经历了许多相关的问题,找不到想要的结果。

例如:如果用户输入5作为输入。我想创建5个文本框,用于输入5个人的姓名和手机。

我该如何实现?

要计数的TextField

  <GridItem xs={12} sm={12} md={12}>
                      <TextField
                        id="sp_Inhouse"
                        label="Number of Pilots Available "
                        type="number"
                        fullWidth
                        className={classes.textField}
                        value={this.state.sp_Inhousecount}
                        error={!!this.state.sp_InhouseError}
                        helperText={this.state.sp_InhouseError}
                        onChange={this.handleChangeInhouse}
                        margin="normal"
                        required
                      />
                    </GridItem>

尝试添加基于按钮单击的文本框。工作正常。但我希望得到解释的结果。

                    <GridItem xs={12} sm={12} md={12}>
                       <Button color="primary" onClick={this.handleCreatePilots}>
                      <AddIcon />  Add Pilots
                      </Button>
                      {this.state.inhouse.map((index) => {
                        return (
                          <div key={index}>
                          <TextField
                            id="sp_Name"

                            label="Name "
                            type="number"
                            fullWidth
                          />
 <TextField
                            id="sp_Mobile"

                            label="Name "
                            type="number"
                            fullWidth
                          />
                          </div>
                        )
                      })
                      }
                    </GridItem>
 handleCreatePilots=()=>{
    this.setState({
      inhouse:[...this.state.inhouse,'']
    })
  }
回复
  • enemo 回复

    循环浏览用户输入的号码。

    const inputs = [];
    
    for (let i = 1; i <= this.state.total; i++) {
      inputs.push(
        <input name={`input-${i}`} onChange={this.onChange} />
      )
    }
    

    渲染输入

    render() {
      return (
       ....
        {inputs}
      ...
      )
    }
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
    <div id="root"></div>
    
    <script type="text/babel">
    
    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          name: 'React',
          total: 0,
          totalInput: '',
          show: false,
        };
      }
    
      add = () => {
        this.setState({
          total: this.state.totalInput
        })
      }
    
      showValues = () => {
        this.setState({
          show: true
        })
      }
    
      onChange = (event) => {
        this.setState({
          [event.target.name]: event.target.value
        })
      }
    
      render() {
    
        const inputs = [];
    
        for (let i = 1; i <= this.state.total; i++) {
          inputs.push(
            <input name={`input-${i}`} onChange={this.onChange} />
          )
        }
        return (
          <div>
            <input onChange={(e) => this.setState({ totalInput: e.target.value})} value={this.state.totalInput}  placeholder="Enter Number" />
            <button onClick={this.add}>Add</button>
            <br />
            {inputs}
             <br />
            <button onClick={this.showValues}>Show Inputs values</button>
            { this.state.show && 
              <pre>{JSON.stringify(this.state, null, 4)}</pre>
            }
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    </script>

  • 贪婪的想念 回复

    这是解决方案。可能需要其他重构。

    Working link https://jsfiddle.net/ogmv3wpu/1/

    class Hello extends React.Component {
     constructor() {
      super();
      this.state= {
       inputSize: 0
      }
     }
     
     handleOnChange(value){
     this.setState({
     inputSize: value.target.value
     });
     }
     
     renderInputs(value){
      const inputs=[];
      for(let i=0; i<value; i++){
        inputs.push(<div key={i}><input  value={Name}}type="text" name="quantity"/></div>)
      }
      return inputs;
     }
     
      render() {
      console.log(this.state.inputSize);
        return (<div>
        <input type="number" name="quantity" min="0" max="99999" onChange={(value)=>this.handleOnChange(value)}/>
        <div>
        {this.renderInputs(this.state.inputSize)}
        </div>
        </div>
        )
      }
    }
    
    ReactDOM.render(
      <Hello name="World" />,
      document.getElementById('container')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="container">
        <!-- This element's contents will be replaced with your component. -->
    </div>