【问题标题】:React Button Click Hiding and Showing ComponentsReact 按钮单击隐藏和显示组件
【发布时间】:2020-04-24 17:30:55
【问题描述】:

我有一个显示和隐藏文本的切换按钮。单击按钮时,我希望它隐藏另一个组件,如果再次单击它会显示它。

我在这里创建了一个repl:

https://repl.it/repls/DapperExtrasmallOpposites

我想保留原始的显示/隐藏文本,但我还想在单击按钮时隐藏一个附加组件。

如何传递该状态或如何创建 if 语句/三元运算符来测试它是处于显示还是隐藏状态。

在上面的 repl 中一切都有意义!

【问题讨论】:

标签: 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>
          )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2016-05-21
      • 1970-01-01
      • 2020-05-21
      • 2012-05-06
      • 1970-01-01
      相关资源
      最近更新 更多