我有这个面包屑组件,可以在道具上进行映射,并提供如下的芯片组件列表:
class BreadCrumb extends React.Component {
render () {
const {
steps,
activeIndex
} = this.props;
const chips = steps
.map((step,index) => {
return <Chip
key={index}
title={step.category}
onClick = {()=> this.props.selectChip(index)} // this should be passed only if
// active == true
active={activeIndex >= index} />
})
return (
<div className="chip-container">
{chips}
</div>
)
}
}
只有当他的活动道具为真时,我才需要点击筹码, 这是芯片组件
class Chip extends React.Component {
render(){
const {
active,
title
} = this.props;
const activeClassName = active ? 'chip active' : 'chip';
return (
<div
className = {activeClassName}
onClick = {() => this.props.onClick()} >
<span>{title}</span>
</div>
)
}
}
仅当活动道具为真时,如何才能使芯片可点击?
有关更多信息,selectChip()函数设置组件App(面包屑组件的父级)的状态,因此将其绑定到App组件。
答案 0 :(得分:3)
执行处理程序或空的function
onClick = {isActive ? this.props.onClick : () =>{} } >
答案 1 :(得分:3)
您可以例如使onClick
用作类方法并在其中使用一个简单条件:
class Chip extends React.Component {
handleClick = () => {
if (this.props.active) {
this.props.onClick(); // call only if active props is true
}
}
render() {
const { active, title } = this.props;
const activeClassName = active ? 'chip active' : 'chip';
return (
<div
className = {activeClassName}
onClick = {this.handleClick}
>
<span>{title}</span>
</div>
)
}
}
答案 2 :(得分:1)
您可以这样做:-
// If chip component expects a function all the time
<Chip
key={index}
title={step.category}
onClick = {step.active ? ()=> this.props.selectChip(index) : () => {}}
active={activeIndex >= index} />
// If onClick is an optional prop to chip component
<Chip
key={index}
title={step.category}
onClick = {step.active ? ()=> this.props.selectChip(index) : undefined}
active={activeIndex >= index} />