reactjs - 与react.js中的ng-if等效的是什么?

标签 reactjs

我正在使用 Angular 使用react,我正在尝试找出一个很好的 React 替代方案来替代 Angular 的 ng-if 指令,在该指令中我根据条件渲染或不渲染元素。以这段代码为例。顺便说一句,我正在使用 typescript (tsx),但这应该不重要。

"use strict";

import * as React from 'react';

interface MyProps {showMe: Boolean}
interface MyState {}

class Button extends React.Component <MyProps, MyState>{
  constructor(props){
    super(props);
    this.state = {};
  }

  render(){
    let button;
    if (this.props.showMe === true){
       button = (
        <button type="submit" className="btn nav-btn-red">SIGN UP</button>
      )
    } else {
      button = null;
    }
    return button;

}
}
export default Button;

这个解决方案是有效的,但是还有其他通常使用的方法来实现这个效果吗?我只是猜测

最佳答案

怎么样ternary operator

render() {
  return (
    this.props.showMe ? <button type="submit" className="btn nav-btn-red">SIGN UP</button> : null
  );
}

您还可以使用&&:

render() {
  return (
    this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>
  );
}

注释中的大块可以通过将 JSX 包装在 () 中轻松处理:

render() {
  return this.props.showMe && (
    <div className="container">
      <button type="submit" className="btn nav-btn-red">
        SIGN UP
      </button>
    </div>
  );
}

也内联:

render() {
  return (
    <div className="container">
      {this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>}
    </div>
  );
}

关于reactjs - 与react.js中的ng-if等效的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36771017/

相关文章:

javascript - 将 React Webpack 应用程序(不是使用 create-react-app 创建的)部署到 Github 页面

mongodb - ReactJS - 如何从 MongoDB Date.now 更改日期格式

css - 有没有办法让 react 选择具有可折叠的组?

reactjs - window.location.href 与 react-router-dom 的重定向实用程序

reactjs - 无法运行 gatsby develop - 加载本地开发命令时出现问题

javascript - React/Redux 应用程序中 js Promise 中 Uncaught Error

javascript - TypeError : _This. Prop 未定义

html - 具有相同类名的不同类在不同组件中单独导入,相互覆盖 - React

javascript - 如何在不直接改变样式的情况下实现悬停效果?

javascript - React 找不到我包含的第三方脚本