【问题标题】:Using an if statement to apply inline style (React)使用 if 语句应用内联样式 (React)
【发布时间】:2019-12-18 14:55:55
【问题描述】:

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

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

<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。

【问题讨论】:

  • 使用三元运算符修复:&lt;div style={{ display: this.props.info.realm !== 3 ? "block" : "none" }} &gt;

标签: reactjs if-statement styles inline


【解决方案1】:

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

在你的情况下,你可以做 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>
);

如果您使用的是类组件,或者使用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>
  );
}

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2013-02-15
    相关资源
    最近更新 更多