React Button Click Hiding and Showing Components

走远了吗. 提交于 2021-01-29 09:47:07

问题


I have a toggle button that show and hides text. When the button is clicked I want it to hide another component and if clicked again it shows it.

I have created a repl here:

https://repl.it/repls/DapperExtrasmallOpposites

I want to keep the original show / hide text but I also want to hide an additional component when the button is clicked.

How to I pass that state or how do I create an if statement / ternary operator to test if it is in show or hide state.

All makes sense in the repl above!


回答1:


To accomplish this you should take the state a bit higher. It would be possible to propagate the state changes from the toggle component to the parent and then use it in any way, but this would not be the preferred way to go.

If you put the state in the parent component you can use pass it via props to the needed components.

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>
      )
  }
}



回答2:


I just looked at your REPL.

You need to have the visibility state in your App component, and then pass down a function to update it to the Toggle component.

Then it would be easy to conditionally render the NewComponent component, like this:

render() {
  return (
    <div className="App">
    {this.state.visibility && <NewComponent />}
    <Toggle setVisibility={this.setVisibility.bind(this)} />
    </div>
  );
}

where the setVisibility function is a function that updates the visibility state.



来源:https://stackoverflow.com/questions/59624519/react-button-click-hiding-and-showing-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!