如何隐藏/显示ReactJS中不同视图重用的组件的内容



我有两个视图调用一个特定的组件,这使得我很难在需要该组件时隐藏/显示。通过这种方式,我有以下内容:

我试着做了一个展示:没有任何东西可以掩盖风格,但这是一个问题。这是因为使用相同组件时的视图,CSS的类被调用相同,并且当我进行显示时:没有,我得到它不显示在"新闻"中,但在"主页"中,它也会影响,并且不会显示给我。

我试过了:

组件部分:

<div className="section_news">
{orden.map(this.renderSection)}
<ViewAllNews mostrarCategorias={false} categoriaId={newsId} />

如果我删除这样的标题,我会离开视图"主页"one_answers"新闻",这不是我打算做的。

接下来,我留下原始代码:

名为"主页"的视图:

<div className="contentbar">
<Section title="Ult. News" />
<Section
notices_id={19}
orden={[[0, 3], [3, 1], [4, 2]]}
/>
</div>

**查看名为"新闻":**

<Section
notices_id={data.post.category.id}
orden={[[0, 2], [2, 3]]}
/>

组件部分:

<div className="section_news">
<Titles title={title || (category && category.title)} />
{orden.map(this.renderSection)}
<ViewAllNews categoriaId={newsId} />

组件视图所有新闻:

return (
<Link to={`/news/c/${categoryId}/`}>
<div className="parentLineViewAll">
<div className="LineViewAll" />
<div className="line" />
<div className="Views">View All</div>
<div className="arrowMore">
<FontAwesomeIcon icon="chevron-circle-right" />
</div>
</div>
</Link>
);
};

如您所见,"主页">《视图》的视图使用了相同的组件。

我真正需要的是为"新闻"视图隐藏名为的组件,并且仅为<strong]"新闻"查看隐藏>的"ViewAllNews"组件

谢谢你的帮助!

隐藏/显示react组件的最简单方法是使用条件呈现

以下是一个基本示例:

class MyComponent Extends React.Component {
constructor(props){
super(props)
this.state = {
isVisible: false, // <-- add a value to state so we can track the components visibility
}
}
show = () => {
this.setState({ isVisible: false })
}
hide = () => {
this.setState({ isVisible: true })
}
render(){
if(this.state.isVisible){
return (
/* your component code */
)
}
}
}

如果你想从父组件内部切换组件,那么你可以用ref:来控制它

class Parent Extends React.Component {
constructor(props){
this.myRef = React.createRef()
}
render(){
return <MyComponent ref={this.myRef}>
}
}

组件安装后,您可以检查ref是否已设置,并在代码中的任何位置调用该方法:

if(this.myRef.current){
this.myRef.current.show() // or .hide()
}

您还可以通过道具控制组件的可见性:

function MyComponent({ isVisible }){
if(isVisible){
return (
/* your component code */
)
}
}

希望这能有所帮助,如果你有任何问题,请告诉我!

实现此CCD_ 1和CCD_,喜欢这个例子,希望对你有所帮助。

最新更新