在开发H5时,公司内没有封装好的下拉多选框组件支持开发,只能自己自力更生啦~
支持多选,支持回填input框:
import React from 'react';
import ReactDOM from 'react-dom';
let regList = []
let regionVal = []
class Region extends React.Component {
constructor(props) {
super(props);
this.state = {
regionArr:[
{label:"河南",value:"0",name:"河南"},
{label:"湖南",value:"1",name:"湖南"},
{label:"江西",value:"2",name:"江西"},
{label:"浙江",value:"3",name:"浙江"},
{label:"长沙",value:"4",name:"长沙"},
{label:"武汉",value:"5",name:"武汉"},
]
};
}
componentDidMount(){
regList = [];
regionVal = [];
const {regionArr} = this.state;
for(var i = 0;i < regionArr.length ; i++){
const tempDiv = document.createElement("div");
const tmpinput = document.createElement("input");
const tmpp = document.createElement("span");
tmpinput.setAttribute("name","regionchexk");
tmpinput.setAttribute("type","checkbox");
tmpinput.setAttribute("id",regionArr[i].value);
tmpinput.setAttribute("style","width:20px;height:20px;border:1px solid grey;margin:5px;margin-right:10%;");
tempDiv.appendChild(tmpinput);
tempDiv.appendChild(tmpp);
tmpp.innerText = regionArr[i].name;
tmpp.setAttribute("style","float:right;margin-right:75%;margin-top:5px")
document.getElementById("selectdiv").appendChild(tempDiv);
}
}
myClick=(e)=>{
document.getElementById("selectdiv").style.display="block";
const {regionArr} = this.state;
document.onclick=function(event){
if(event.target.name === 'regionchexk'){
console.log(event.target.name);
if(event.target.checked){
regList.push(regionArr[event.target.id].name)
regionVal.push(event.target.id);
}else{
for(var i = 0 ;i<regList.length;i++){
if(regList[i] === regionArr[event.target.id].name){
regList.splice(i,1)
regionVal.splice(i,1)
}
}
}
document.getElementById("selectButton").value = regList
document.getElementById("selectdiv").style.display = "none";
}
};
}
render() {
return (
<div>
<span style={{width:"100%",height:"20px",overflow:"hidden"}}>
<input type="text" id="selectButton" onClick={()=>{this.myClick()}} placeholder="请输入地市" readOnly={true} style={{width:"200px",height:"20px",fontSize:"14px"}}></input>
</span>
<span id="selectdiv" style={{display:"none",border:"1px solid black",width:"100%",overflowY :"scroll",height:"60px",backgroundColor:"white",fontSize:"14px" }}>
</span>
</div>
);
}
}
ReactDOM.render(<Region/>,document.getElementById
('root'))

本文介绍了在React开发中如何自定义一个下拉多选框组件,该组件具备多选和输入框回填功能,适用于H5开发场景。

1307

被折叠的 条评论
为什么被折叠?



