附加具有动态创建的输入字段的图像,无需重复

时间:2018-11-06 16:48:24

标签: reactjs

我的代码通过让用户输入数字以指定创建inputfields的时间来动态创建带有附加按钮的多个输入字段。 我的问题:如果我尝试将一个图像附加到一个inputfield,并重复另一个inputfield,这是不正确的。我需要每个图像都附加其inputfield,而不是所有。我对reactjs不熟悉,在此先感谢您的帮助,以下是我的代码

 import React, { Component } from 'react';
    import './App.css';

    class App extends Component {
     state = {
          number: 0,
          list: [],
          imagePreviewUrl : '',
          file : ''
        };


      handleChange = e => {
        this.setState({ number: Number(e.target.value) });
      };

      handleClick = () => {  
        if(this.state.number > 30){
         alert('Not Allowed To Use Number Older Than 30')
        }else{
        const list = new Array(this.state.list.length + this.state.number).fill();
        this.setState({ list });
        }
        if(this.state.list.length !== 0){
          this.setState({ list : [] })
          this.setState({ imagePreviewUrl : ''})
          this.setState({ file : ''})
        }
      };


      onClear = () => {
        this.setState({ list: [] });
        this.setState({ imagePreviewUrl : ''})
        this.setState({ file : ''})
      };



     _handleImageChange(e) {
      e.preventDefault();
      let reader = new FileReader();
      let file = e.target.files[0];
      reader.onloadend = () => {
        this.setState({
          file : file,
          imagePreviewUrl: reader.result
        });
      }
      reader.readAsDataURL(file)
      } 

      handleChange(e,item){
        this.setState.list[item]= e.target.value
        //set the changed state
        const list = new Array(this.state.list.length + this.state.number).fill();
        this.setState({ list }); 
      }


      renderInputs = () => {
        return this.state.list.map(item => 
        <div key={item}>
                    <input  onChange={(e)=>this.handleChange(e,item)} placeholder="Phone"/>
                    <input 
                    style={{display :'none'}} 
                    type="file" 
                    onChange={(e)=>this._handleImageChange(e,item)}
                    ref={fileInput => this.fileInput = fileInput}
                    />
                    <button onClick={() => this.fileInput.click()}>Image</button>
                    <img src={this.state.imagePreviewUrl} width="50" height="50" alt=''/>
        </div>);
      };



      render() {
        return (
          <div className="App">
            <div>
              <input min="0" max="30" type="number" onChange={this.handleChange} />
              <button onClick={this.handleClick}>Add</button>
              <button type="button" onClick={this.onClear}>Clear</button>
              <button>Save</button>
            </div>
            <div>
             {this.renderInputs()}
            </div>
          </div>
        );
    }  
    }
    export default App;

1 个答案:

答案 0 :(得分:1)

更改以下方法,使其看起来像这样:

_handleImageChange(i, e) {
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];
    reader.onloadend = () => {
        // update this.state.list with the image data at the appropriate index
        this.setState(prevState => {
            const list = [...prevState.list];
            list[i] = {
                file: file,
                imagePreviewUrl: reader.result
            };
            return {list};
        });
    };
    reader.readAsDataURL(file);
}

renderInputs() {
    return this.state.list.map((item, i) => (
        <div key={i}>
            <input onChange={e => this.handleChange(e)} placeholder="Phone"/>
            <input
                style={{display: 'none'}}
                type="file"
                onChange={e => this._handleImageChange(i, e)}
                ref={`image${i}`}
            />
            <button onClick={() =>this.refs[`image${i}`].click()}>Image</button>
            <img src={!!item ? item.imagePreviewUrl : ''} width="50" height="50" alt='' />
        </div>
    ));
}

此外,您目前有两种名为handleChange的方法,因此您可能想重命名其中一种。