gpt4 book ai didi

javascript - 有条件地将函数作为 props 传递给组件

转载 作者:行者123 更新时间:2023-12-04 15:52:59 25 4
gpt4 key购买 nike

我有这个面包屑组件,它映射 Prop 并呈现如下芯片组件列表:

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>
)
}
}

只有当他的事件 Prop 为真时,我才需要点击筹码,这是芯片组件

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>
)

}
}

只有在 active 属性为 true 的情况下,我才能使芯片可点击?

更多信息 selectChip() 函数设置组件 App 的状态,Breadcrump 组件的父级,因此它被绑定(bind)到 App 组件。

最佳答案

你可以例如将 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>
)

}
}

关于javascript - 有条件地将函数作为 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com