如何隐藏组件是反应并显示另一个组件?

时间:2018-03-01 01:18:16

标签: javascript reactjs react-router

你能告诉我如何在reactJS中隐藏组件并显示另一个组件吗?我有一个按钮和文本(hello)。点击按钮,我想要隐藏按钮和文本并显示另一个文字bye 这是我的代码 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>
    );
  }

3 个答案:

答案 0 :(得分:0)

{ validForm }正在创建一个属性为validForm且值为validForm的对象(例如true或false)。您可以阅读更多相关信息here。您的代码应如下所示

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

答案 1 :(得分:0)

一种方法是先将它放在一个单独的变量上

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

答案 2 :(得分:0)

您应该注意一些事项。首先,您要切换validForm状态,所以在showBankDetail函数中执行此操作。您可以根据validForm返回不同的元素,但也可以内联。参见:

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