【问题标题】:React Button Click Hiding and Showing ComponentsReact 按钮单击隐藏和显示组件
【发布时间】:2020-04-24 17:30:55
【问题描述】:
【问题讨论】:
标签:
reactjs
state
react-props
【解决方案1】:
我刚刚看了你的 REPL。
您需要在您的 App 组件中拥有可见性状态,然后传递一个函数以将其更新到 Toggle 组件。
那么就很容易有条件地渲染 NewComponent 组件,像这样:
render() {
return (
<div className="App">
{this.state.visibility && <NewComponent />}
<Toggle setVisibility={this.setVisibility.bind(this)} />
</div>
);
}
其中setVisibility 函数是更新可见性状态的函数。
【解决方案2】:
要做到这一点,您应该将状态提高一点。可以将切换组件的状态更改传播到父组件,然后以任何方式使用它,但这不是首选方式。
如果您将状态放在父组件中,您可以通过 props 将其传递给所需的组件。
import React from "react";
export default function App() {
// Keep the state at this level and pass it down as needed.
const [isVisible, setIsVisible] = React.useState(false);
const toggleVisibility = () => setIsVisible(!isVisible);
return (
<div className="App">
<Toggle isVisible={isVisible} toggleVisibility={toggleVisibility} />
{isVisible && <NewComponent />}
</div>
);
}
class Toggle extends React.Component {
render() {
return (
<div>
<button onClick={this.props.toggleVisibility}>
{this.props.isVisible ? "Hide details" : "Show details"}
</button>
{this.props.isVisible && (
<div>
<p>
When the button is click I do want this component or text to be
shown - so my question is how do I hide the component
</p>
</div>
)}
</div>
);
}
}
class NewComponent extends React.Component {
render() {
return (
<div>
<p>When the button below (which is in another component) is clicked, I want this component to be hidden - but how do I pass the state to say - this is clicked so hide</p>
</div>
)
}
}