Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从输入文件设置背景图像?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何从输入文件设置背景图像?

Javascript 如何从输入文件设置背景图像?,javascript,reactjs,Javascript,Reactjs,我希望从输入的本地文件设置背景图像 但它会出现“net::ERR\u UNKNOWN\u URL\u SCHEME”错误消息 我的输入标签: <input accept="image/*" className="input_img" type="file" onChange={e => this.uploadImage(e)} /> 如何操作?您可以使用读取文件的数据,然后使用结果设置背景图像 示例 class App extends Component {

我希望从输入的本地文件设置背景图像

但它会出现“net::ERR\u UNKNOWN\u URL\u SCHEME”错误消息

我的输入标签:

<input
  accept="image/*"
  className="input_img"
  type="file"
  onChange={e => this.uploadImage(e)}
/>
如何操作?

您可以使用读取文件的数据,然后使用结果设置
背景图像

示例

class App extends Component {
  uploadImage = (e) => {
    const { files } = e.target;
    if (files.length === 0) {
      return;
    }

    const file = files[0];
    const fileReader = new FileReader();

    fileReader.onload = () => {
      this.background.style.backgroundImage = `url(${fileReader.result})`;
    };
    fileReader.readAsDataURL(file);
  };

  render() {
    return (
      <div>
        <input
          accept="image/*"
          className="input_img"
          type="file"
          onChange={this.uploadImage}
        />
        <div
          style={{width: 200, height: 200}}
          ref={ref => this.background = ref}
        ></div>
      </div>
    );
  }
}
类应用程序扩展组件{
上传图像=(e)=>{
const{files}=e.target;
如果(files.length==0){
返回;
}
常量文件=文件[0];
const fileReader=new fileReader();
fileReader.onload=()=>{
this.background.style.backgroundImage=`url(${fileReader.result})`;
};
fileReader.readAsDataURL(文件);
};
render(){
返回(
this.background=ref}
>
);
}
}

I添加'onChange={e=>this.uploadImage(e)},它可以工作!谢谢大家!@高妈真棒!没问题。
class App extends Component {
  uploadImage = (e) => {
    const { files } = e.target;
    if (files.length === 0) {
      return;
    }

    const file = files[0];
    const fileReader = new FileReader();

    fileReader.onload = () => {
      this.background.style.backgroundImage = `url(${fileReader.result})`;
    };
    fileReader.readAsDataURL(file);
  };

  render() {
    return (
      <div>
        <input
          accept="image/*"
          className="input_img"
          type="file"
          onChange={this.uploadImage}
        />
        <div
          style={{width: 200, height: 200}}
          ref={ref => this.background = ref}
        ></div>
      </div>
    );
  }
}