javascript - 文件输入未正确更新状态 React?

标签 javascript reactjs

好吧,我有一个表单,上面有图像的文件输入(并且在提交之前预览图像),但只有第一个输入更新(无论我使用哪个输入来放置图像)。

以下是重现步骤:

  1. 点击“添加问题”按钮两次或多次
  2. 点击(因为还无法放置)第二个放置区并上传文件。
  3. 看到第一个拖放区更新,而不是第二个

Here's a CodeSandbox for it.

这是我的放置区组件的代码:

class DropZone extends Component {

    constructor(props){
      super(props)
      this.state = {
        file: "",
        fileId: uuid()
      }
      this.handleChange = this.handleChange.bind(this)

    }

    handleChange(event) {
      this.setState({
        file: URL.createObjectURL(event.target.files[0])
      })
      //document.getElementsByClassName("dropZone").style.backgroundImage = 'url(' + this.state.file + ')';
    }

  render() {
    return (
      <div >
        <input type="file" id="file" name="file" class="inputFile" onChange={this.handleChange}/>
        <label  key={uuid()} for="file" value={this.state.file} onchange={this.handleChange}>
          <div class="dropZone" key={uuid()}>
            Drop or Choose File
            <img src={this.state.file} id="pic" name="file" accept="image/*"/>
          </div>
        </label>
        <div>
      </div>
      </div>
    );
  }
}

我是 React 和 JS 的新手,所以任何解释都会有帮助。谢谢!

最佳答案

这不是 React 的问题,而是 HTML 绑定(bind)的问题。您需要为输入框和 label htmlFor 属性提供唯一的 id。我已经更新了下面的代码。以及您的代码沙箱 -> https://codesandbox.io/s/kkj7j61noo

class DropZone extends Component {

    constructor(props){
      super(props)
      this.state = {
        file: "",
        fileId: uuid()
      }
      this.handleChange = this.handleChange.bind(this)

    }

    handleChange(event) {
      this.setState({
        file: URL.createObjectURL(event.target.files[0])
      })
      //document.getElementsByClassName("dropZone").style.backgroundImage = 'url(' + this.state.file + ')';
    }

  render() {
    const uniqueId = this.state.fileId;
    return (
      <div >
        <input type="file" id={uniqueId} name={uniqueId} class="inputFile" onChange={this.handleChange}/>
        <label  key={uuid()} htmlFor={uniqueId} value={this.state.file}>
          <div class="dropZone" key={uuid()}>
            Drop or Choose File
            <img src={this.state.file} id="pic" name="file" accept="image/*"/>
          </div>
        </label>
        <div>
      </div>
      </div>
    );
  }
}

关于javascript - 文件输入未正确更新状态 React?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51562553/

相关文章:

javascript - 我正在使用 focusin/focusout 并且得到 : Uncaught TypeError: Cannot read property 'addEventListener' of null

javascript - 使用 Karma : "module is not defined" 进行 Angular Testing

javascript - 如何在 React 中修改对象属性

javascript - 更新单个元素的状态(其余默认为常量)

javascript - Formik:将 Material UI Date Picker 作为 prop 传递给 React Component 时,目标未定义

javascript - getElementById 在本地测试但在 JSFiddle 中工作时返回 null

javascript - Meteor:我可以使用什么来代替 setTimeout 来响应 DOM 更改?

javascript - 在 React 中从 <h4> 获取值

javascript - 如何检测 HTML 元素是否是 React 组件的根?

javascript - 在 React Native 中调用自定义组件的 onPress