[英]How do I render component based on state
I've got this filter Icon from MaterialUI and I need it to be filled black (for now it can change position) when a checkmark is checked.我从Metteralui中获得了此过滤器图标,当检查检查标记时,我需要将其填充为黑色(现在可以更改位置)。 When a box is checked setFilters is filled.当一个框被选中时,setFilters 被填充。 So if a check is Product Type is ticked, setFilters(prt:[]) wont be empty.因此,如果勾选了产品类型,则 setFilters(prt:[]) 不会为空。
How do I make it so that if setFilters(prt:[]) is not empty, I can render the filter icon with a different position (eventually i'll render a different icon).如何做到这一点,以便如果 setFilters(prt:[]) 不为空,我可以使用不同的 position 呈现过滤器图标(最终我将呈现不同的图标)。
I've already tried我已经试过了
{ props.filters > 0 && d.autoFilter? <FiFilter style={{position:"relative", top:"4px", left: "12px"}} onClick={() => props.toggleVisibleFilter(d.field)}/>:<div/>}
// component A const [filters, setFilters] = useState({search:'',prt:[],cnt:[],cat:[]}) // Component B const headerFields = [ {field: 'ID', label: '', width: '5%'}, {field: 'bnd', label: 'Brand', width: '15%' }, {field: 'cnt', label: 'Country', autoFilter: true, width: '15%' }, {field: 'prt', label: 'Product type', autoFilter: true, width: '20%' }, {field: 'cat', label: 'Category', autoFilter: true, width: '20%' }, {field: 'url', label: 'URL', width: '25%' }, ] // JSX <TableRow> {headerFields.map((d)=> <TableCell classes={{ root:classes.root }} style={{ textAlign:"left",fontSize:"18px", position:"sticky", width:d.width, background:"#F28808"}} align="left">{d.label} { d.autoFilter? <FiFilter style={{position:"relative", top:"4px", left: "4px"}} onClick={() => props.toggleVisibleFilter(d.field)}/>:<div/>} {props.visibleFilter===d.field?<MultiSelectFIlter filterHandler={props.filterHandler} API_DATA={props.API_DATA} visibleFilter={props.visibleFilter} setVisibleFilter={props.setVisibleFilter} setFilters={props.setFilters} filters={props.filters} />:(null)} </TableCell> )} </TableRow>
You can use conditional approach like this您可以使用这样的条件方法
style={`${filters==[]} ? {display:"none"} : {display:"block"} `}
From your conditional above, you have an error.从上面的条件来看,您有一个错误。 For when you check if the array is empty or not you must check the length of it not just props.filters
but instead props.filters.length
in order for the conditional to work, otherwise while array is defined and the length is 0 the props.filters
will always return true;因为当您检查数组是否为空时,您必须检查它的长度,而不仅仅是props.filters
而是props.filters.length
以使条件起作用,否则当定义数组并且长度为 0 时, props.filters
将始终返回 true;
also since in your case you have defined it like:还因为在您的情况下,您已将其定义为:
const [filters, setFilters] = useState({search:'',prt:[],cnt:[],cat:[]})
your conditional should be something like this:你的条件应该是这样的:
{ props.filters.prt.length > 0 ? ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.