NatChen

Once you have chosen the road of life, you have to be brave enough to go to the end and never look back.

我们一起踩过的坑----react(antd)(二)

1.antd Upload默认值问题

需求是这样的,后台若没有图片默认值,则只有上传按钮,且只能上传一张图片;若有默认值,则显示默认头像图片, 可删除,删除之后有且只能添加一张图片,没有删除默认图片时不能添加图片

坑爹之路漫漫-----

 

图为无默认值时状态

图为有默认值状态,删除后可添加图片

首先设置defaultFileList,但是defaultFileList并不会默认添加到fileList里面

<Upload
accept="image/*"
listType= 'picture'
beforeUpload={this.beforeUpload}
defaultFileList={fieldValue?[{
uid:"-1",
status: 'done',
url: `/file-server/${fieldValue}`,
}]:""}
onChange={this.handleChange}
>
{
this.state.fileList.length>=1?"":<Button style={{width:this.props.width}}>
<Icon type="upload" /> 点击上传
</Button>
}
</Upload>


 2.antd表格筛选问题

antd官网上 https://ant.design/components/table-cn/#components-table-demo-custom-filter-panel

只有单列表格筛选的栗子,并没有全部表格筛选功能,坑爹啊~

需求如下:在右上角搜索,所有列搜索

首先是布局,因为我用了<Card>,所以用了extra属性,添加了一个input框,

<Card
title={cardTitle}
id={cardTitle}
className="hoverable"
headStyle={{background:"#f2f4f5"}}
extra={this.props.type==="detail"?<Input placeholder="关键字搜索"
onChange={this.searchValue}
addonBefore={<Icon type="search"/>}
/>:""}
>
</Card>

在引入react-highligt-words插件

import Highlighter from 'react-highlight-words';

还要去除封面和序号的干扰,直接上代码,写的不好

searchValue=(e)=>{
const {columns,dataSource}=this.props
const txt=e.target.value
const data=[]
columns.forEach((item)=>{
const id=item.id;
if(item && item.type!=="file"){
if(e.target.value){
const arr=[]
arr.push(...dataSource.filter(item=>typeof item[id]==="string" && item[id].includes(txt)===true))
//匹配到一行两个条件,去重
for(let i=0;i<arr.length;i++){
  let flag = true;
  for(let j=0;j<data.length;j++){
    if(Object.is(arr[i], data[j])===true){ //判断两个对象是否相同
      flag = false;
    }
  };
  if(flag){
data.push(arr[i]);
  };
};
}else{
if(data.includes(...dataSource)===false){
data.push(...dataSource)
}
}
item["render"]=text =>
<Highlighter
highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
searchWords={[this.state.searchText]}
autoEscape
textToHighlight= {text?text.toString():""}
/>
}
})
this.setState({
searchText:e.target.value,
dataSource:data
})
}

如果input框有数据输入,用filter筛选,push进data,再将data赋给页面渲染

如果input为空,即不用筛选,将所有数据都显示出来 ,最后实现效果如图:

 

 

3.antd模态框组件更新问题

不知道大家有没有遇到过这种情况,第一次加载模态框,数据很好的显示出来了,第二次再点击别的模态框的时候,呈现的还是第一次加载的数据,这是为什么呢???

之后各种去翻数据,传的是否有问题,但是显示数据没问题,后来在 componentDidMount中加入输出,监测到模态框只在第一次加载的时候更新数据,第二次加载其实是没有加载的,究其原因,其实是因为你点击关闭模态框的时候,只是隐藏了模态框,并没有销毁组件····坑

解决方法:在modal中加入destoryOnClose,问题迎刃而解啦,哈哈哈哈哈

<Modal
title={this.props.title}
visible={this.props.visibleForm}
onOk={this.handleOk}
onCancel={this.props.handleCancel}
okText="确认"
cancelText="取消"
destroyOnClose
>

  

posted @ 2018-12-28 18:14  NatChen  阅读(3082)  评论(0编辑  收藏  举报