简体   繁体   中英

how to hide component is react and show another component?

could you please tell me how to hide the component in reactJS and show another component?I have one button and text ( hello ).on button click, I want to hide button as well as text and show another text bye here is my code https://codesandbox.io/s/50lj63xvk

showBankDetail = () => {
    console.log("====");
    this.setState({
      validForm: true
    });
  };
  render() {
    const validForm = !this.state.validForm;
    return { validForm } ? (
      <div>
        heloo<button onClick={this.showBankDetail}>hide</button>
      </div>
    ) : (
      <div>bye</div>
    );
  }

{ validForm } is creating an object with property validForm and value of validForm (eg true or false). You can read more about it here . Your code should look like this

showBankDetail = () => {
  console.log("====");
  this.setState({
    validForm: true
  });
};
render() {
  const validForm = !this.state.validForm;
  return validForm ? (
    <div>
      heloo<button onClick={this.showBankDetail}>hide</button>
    </div>
  ) : (
    <div>bye</div>
  );
}

One way is to put it on a separate variable first

showBankDetail = () => {
  console.log("====");
  this.setState({
    validForm: true
  });
};

render() {
  const validForm = !this.state.validForm;
  let form;
  if (validForm) {
    form = (<div>
            heloo<button onClick={this.showBankDetail}>hide</button>
          </div>);
  } else {
    form = (<div>bye</div>);
  }
  return ({form});
}

There are a few things you should look at. First off you want to toggle the validForm state, so do that in the showBankDetail function. You could return different elements based on validForm, but you can also do it inline. See:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      validForm: false
    };
  }
  showBankDetail = () => {
    this.setState({
      validForm: !this.state.validForm
    });
  };
  render() {
    return (
      <div>
        { this.state.validForm ?
          <div>heloo</div> :
          <div>bye</div>
        }
        <button onClick={this.showBankDetail}>hide</button>
      </div>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM