使用 if 语句应用内联样式 (React)

Using an if statement to apply inline style (React)

我想使用 React 的内联样式来应用条件渲染。

事情是:我有一个道具可以根据场景吐出 1、2 或 3。所以我希望当输出为 1 或 2 时,出现 div(显示:'block'),但是当输出为 3 时,设置为 none。

<div style={{
            display: () => {
              if (this.props.info.realm === 1 || this.props.info.realm === 2) {
                console.log("this has to be block");
                return "block";
              } else {
                console.log("this has to be none");
                return "none";
              }
            }
          }}>

          <p>Hola</p>
</div>

当这段代码运行时,除了唯一的 Div,我什么也得不到。甚至 console.logs.

您需要调用函数才能获取值;

在您的情况下,您可以执行 IIFE(立即调用的函数表达式):

      <div style={{
            display: (() => {
              if (this.props.info.realm === 1 || this.props.info.realm === 2) {
                console.log("this has to be block");
                return "block";
              } else {
                console.log("this has to be none");
                return "none";
              }
            })()
          }}>
          <p>Hola</p>
      </div>

或者,您可以在 render 方法之外进行

function getDisplay() {
  if (this.props.info.realm === 1 || this.props.info.realm === 2) {
    return "block";
  }
  else {
    return "none";
  }
}

return (
  <div style={{ display: getDisplay() }}>
    <p>Hola</p>
  </div>
);

或者如果您使用的是 class 组件,则使用 getter 使其更清洁:

get display() {
  if (this.props.info.realm === 1 || this.props.info.realm === 2) {
    return "block";
  }
  else {
    return "none";
  }
}

render() {
  return (
    <div style={{ display: this.display }}>
      <p>Hola</p>
    </div>
  );
}