开头
基础 使用javascript 透过按钮新增删除栏位进阶 新增图片并有图片预览功能基础
Demo:
https://codepen.io/Candas/pen/pdRwLb
先做出基础:新增删除栏位,观念是设定一个阵列,新增就是array.push 一个元素,删除就是 array.splice 移除一个元素,显示出这些栏位而是用map()去跑阵列。
新增:因为push需要有东西给他塞进去,所以我们就新增input的name属性,
然后再this.setState() 更新 input
appendInput(e) { e.preventDefault(); this.state.inputs.push({ name: null }); this.setState({ inputs: this.state.inputs }); }
删除:index为当前阵列最尾端,使用array.splice 从index位置开始移除一个元素,并用this.setState 更新 input
splice()
removeInput(index) { this.state.inputs.splice(index, 1); this.setState({ inputs: this.state.inputs, }); }
<input>
列表
在 render()下面定变数 inputList ,将input.map出来就会出现<input>
的列表
let inputList = this.state.inputs.map((input, index) => { let ref = "input_" + index; return ( <div key={index}> <input type="file" key={input} ref={ref} /> <button id={ref} onClick={this.removeInput.bind(this, index)}> 删除 </button> </div> ); });
进阶
Demo:
https://codepen.io/Candas/pen/jayGWv?editors=0010
这次新增了图片预览,直接看code
图片预览
会用会用到 FileReader()
跟用·e.target
抓栏位资讯 不懂可用consol.log
看他们在干嘛
reader.onloadend()是FileReader的函式,handleImageChange()
主要概念呢一样 用一个 Array 储存reader.result
也就是本地的图片网址 图片预览图片预览其实就是用本地网址去读取,目前建议改用WINDOW.URL.CREATEOBJECTURL
因为FileReader
会把图片转成base-64 档案比较大 图片太大会loading 不优,
这边有个小技巧
这是当你回心转意 设完栏位上传完图片还想再改图片就需要用它防止bug,不信等等下课把他删掉你就知道了
,因为图片预览一样是用push()去加 如果想要在新增栏位会继续push 所以要确认说 你目前是array长度有没有超过当前的长度,没有就改该位置的图片网址就好
if (this.state.imagePreviewList.length < index) { this.state.imagePreviewList.push(reader.result); } else { this.state.imagePreviewList[index] = reader.result; }
// 图片大预览建议使用 WINDOW.URL.CREATEOBJECTURL handleImageChange(e, index) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0]; console.log(reader); reader.onloadend = () => { // 假设目前不是修改预览图片 那就新增预览图片 if (this.state.imagePreviewList.length < index) { this.state.imagePreviewList.push(reader.result); } else { this.state.imagePreviewList[index] = reader.result; } this.setState({ file: file, imagePreviewList: this.state.imagePreviewList }); }; console.log(this.state.imagePreviewList); reader.readAsDataURL(file); }
结语
2018 铁人赛要到了,不过我目想参加,为了不断文章很累啊,平常当铁人就好,不要比赛在当