我正在使用React钩子,下面是我想在sortDirection
是状态的情况下实现的条件渲染。我想基于<i>
渲染sortDirection
标签之一。我该如何实现?
if (sortDirection == "ascending") {
return <i onclick={() => setSortDirection('descending')} className="fa fa-arrow-down" />
} else if (sortDirection == "descending") {
return <i onClick={() => setSortDirection('random')} className="fa fa-arrow-up" />
} else {
return <i onClick={() => setSortDirection('ascending')} className="fa fa-arrow-h" />
}
答案 0 :(得分:1)
您可以只创建一个单独的功能组件并将条件作为道具
const MyIComponent = (sortDirection) => {
if (sortDirection == "ascending") {
return <i onclick={() => setSortDirection('descending')} className="fa fa-arrow-down" />
} else if (sortDirection == "descending") {
return <i onClick={() => setSortDirection('random')} className="fa fa-arrow-up" /> }
return <i onClick={() => setSortDirection('ascending')} className="fa fa-arrow-h" />
}
const MainComponent = () => <myIComponent sortDirection={sortDirection} />
答案 1 :(得分:0)
const MyIComponent =({sortDirection,iClassName})=> { 返回setSortDirection(sortDirection)} className = {iClassName} /> }
您可以从主要组件动态传递sortDirection和iClassName作为道具,然后在有条件的情况下也可以避免