ReactJS - 从切换按钮传递状态以隐藏 Div

ReactJS - Passing state from a toggle button to hide a Div

在 React 项目中,我有一个切换按钮,可以向用户显示和隐藏一些信息。现在我想将第三方连接到切换。

例如,当页面加载时显示 div,然后单击切换按钮然后我希望它隐藏。

我需要知道,如何将状态从一个组件传递到另一个组件以显示可见性。

我在这里创建了一个REPL:

https://repl.it/repls/AcceptableLoyalApplicationsuite

如何根据用户点击将要知道的状态传递给 hide/show?

干杯!

编辑:

所以我需要检查 show/hide 组件的状态。

if statement or state check to show / hide 
<Component />

您可以像下面提到的那样在父组件中定义状态和功能并传递给子组件。

只需更改这两个组件

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