我正在使用React Hooks,以下是我想在sortDirection
为状态的情况下实现的条件渲染。我想基于sortDirection
渲染<i>
标签之一。我该如何实现?
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" />
}
您只需创建一个单独的功能组件,并将条件作为prop
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} />
const MyIComponent = ({sortDirection, iClassName}) => {
return <i onclick={() => setSortDirection(sortDirection)} className={iClassName} />
}
您可以将sortDirection
和iClassName
从主组件中动态传递,作为道具,如果您也可以避免。