反应切换组件 [英] React toggle component
问题描述
我在下面有这个简单的代码。当我按下切换按钮时,组件Child应隐藏/显示,但它不是。
I have this simple code below. When I press the Toggle Button the component Child should hide/show, but it's not.
我是否需要重新渲染某些内容?
我不想切换/退出CSS类,只需通过点击按钮切换
Do I have to re-render something? I don't want to switch in/out a CSS class, just toggle via a button click
import React, {Component} from 'react';
let active = true
const handleClick = () => {
active = !active
}
class Parent extends React.Component {
render() {
return (
<div>
<OtherComponent />
{active && <Child />}
<button type="button" onClick={handleClick}>
Toggle
</button>
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
I am the child
</div>
)
}
}
class OtherComponent extends React.Component {
render() {
return (
<div>
I am the OtherComponent
</div>
)
}
}
推荐答案
您需要通过状态获取或设置它:
You need to get or set it via state:
class Parent extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
active: true,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
active: !this.state.active
});
}
render() {
return (
<div>
<OtherComponent />
{this.state.active && <Child />}
<button type="button" onClick={this.handleClick}>
Toggle
</button>
</div>
)
}
}
注意通过这种方法你将重新:渲染整个父组件(以及它的子组件)。
考虑使用另一种方法,当您将 prop
传递给子组件时,它将使用基于此prop的内容呈现自身(它可以呈现空 div
或者什么)。
有很多库可以让你轻松完成这项工作,例如反应崩溃与动画和stu ff。
Note that with this approach you will re:render the entire parent component (as well as it's children).
Consider using another approach, when you are passing a prop
to the child component and it will render itself with content based on this prop (it can render an empty div
or something).
There are number of libraries that make this job easy for you, like react-collapse with animations and stuff.
这篇关于反应切换组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!