英文:
ReactJS - Passing state from a toggle button to hide a Div
问题
在一个React项目中,我有一个切换按钮,用于向用户显示和隐藏一些信息。现在我想要连接一个第三方组件到这个切换按钮。
例如,当页面加载时,一个div被显示,然后点击切换按钮后,我希望它隐藏。
我需要知道,如何将一个组件的状态传递给另一个组件以显示或隐藏。
我在这里创建了一个REPL:
https://repl.it/repls/AcceptableLoyalApplicationsuite
如何传递状态以便根据用户的点击来隐藏/显示?
干杯!
编辑:
所以我需要检查状态来显示/隐藏组件。
使用if语句或状态检查来显示/隐藏
<Component />
英文:
In a React project, I have a toggle button that shows and hides some info to the user. Now I want to connect a third part to the toggle.
For instance, a div is shown on when the page loads, then the toggle button is clicked then I want that to hide.
I need to know, how do I pass the state from one component to another to show visibility.
I have created a REPL here:
https://repl.it/repls/AcceptableLoyalApplicationsuite
How do I pass the state to know to hide/show based on users clicking?
Cheers!
Edit:
So I need to check the state to show/hide the component.
if statement or state check to show / hide
<Component />
答案1
得分: 1
你可以在父组件中像下面这样定义状态和函数,并传递给子组件。
只需更改这两个组件:
App.js
class App extends React.Component {
state = {
visibility: false
};
handleToggleVisibility = () => {
this.setState(prevState => ({ visibility: !prevState.visibility }));
};
render() {
return (
<div className="App">
<header className="App-header">
<Test />
<Button
visibility={this.state.visibility}
handleToggleVisibility={this.handleToggleVisibility}
/>
</header>
</div>
);
}
}
Button.js
export default class Button extends Component {
render() {
return (
<div>
<em>I have another Div with the className of iNeedToHide</em>
<br />
<button onClick={this.props.handleToggleVisibility}>
{this.props.visibility ? "Hide details" : "Show details"}
</button>
{this.props.visibility && (
<div>
<p>
嘿,这些是一些你现在可以看到的细节!当你看到我时,上面的名为iNeedToHide的div需要被隐藏!但是怎么做?!如何传递这个状态呢?
</p>
</div>
)}
</div>
);
}
}
你的工作代码的实时演示 Live
英文:
You can define state & function in parent component like mentioned below and pass to child components.
Just change these two components
App.js
class App extends React.Component {
state = {
visibility: false
};
handleToggleVisibility = () => {
this.setState(prevState => ({ visibility: !prevState.visibility }));
};
render() {
return (
<div className="App">
<header className="App-header">
<Test />
<Button
visibility={this.state.visibility}
handleToggleVisibility={this.handleToggleVisibility}
/>
</header>
</div>
);
}
}
Button.js
export default class Button extends Component {
render() {
return (
<div>
<em>I have another Div with the className of iNeedToHide</em>
<br />
<button onClick={this.props.handleToggleVisibility}>
{this.props.visibility ? "Hide details" : "Show details"}
</button>
{this.props.visibility && (
<div>
<p>
Hey. These are some details you can now see! When you see me the
div above called iNeedToHide needs to be hidden! But how?! How do
I pass that state?!
</p>
</div>
)}
</div>
);
}
}
Live demo of your working code Live
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论