React:通过 calc() 函数使用内联样式

这篇简短而直接的文章向您展示了在 React 中使用内联样式时如何使用 CSS calc()函数。

概述

calc() 函数计算属性的值(加法、减法、乘法和除法运算):

calc(expression)

如果您的表达式不包含任何变量,您可以用一对单引号或双引号将其括起来:

<div style={{width: 'calc(100% - 99px)'}}></div>

另一方面,如果您的表达式涉及变量,您可以使用带有反引号 (`) 字符的模板文字(模板字符串),如下所示:

<div style={{width: `calc(100% / ${columns.length})`}}></div> 

为了更好地理解和更清晰,请参阅下面的完整示例。

完整示例

演示

我们将要使用的小应用程序提供了一个按钮和一个由一行列构成的布局。按下按钮时,将添加一个新列。列的宽度被平均划分(在 calc() 函数的帮助下)。此外,列中文本的字体大小也随着列数的增加而减小。

以下是它的工作原理:

React:通过 calc() 函数使用内联样式

编码

  1. 创建一个新的 React 项目(以确保我们有相同的起点):
npx create-react-app kindacode-calc-example

名字无所谓。

2. 使用以下命令删除src/App.js中所有不需要的代码:

// KindaCode.com
// src/App.js
import { useState } from 'react';

function App() {
  // This state holds the columns of the layout
  const [columns, setColumns] = useState([{ id: 1, name: 'Column 1' }]);

  // Add a new column
  // This function is called when the user clicks the "Add Column" button
  const addColumn = () => {
    const newColumns = [...columns];
    newColumns.push({
      id: newColumns.length + 1,
      name: `Column ${newColumns.length + 1}`,
    });
    setColumns(newColumns);
  };

  return (
    <div style={{ padding: 30 }}>
      <h2>Welcome to KindaCode.com</h2>
      {/* This button is used to add new columns */}
      <button onClick={addColumn} style={{ padding: '10px 30px' }}>
        Add Column
      </button>

      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          marginTop: 30,
        }}
      >

        {/* Render the columns */}
        {columns.map((column) => (
          <div
            key={column.id}
            style={{
              // Divide the width equally
              width: `calc(100% / ${columns.length})`, 
              height: 300,
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              background: '#3f51b5',
              // The more columns, the smaller the font size
              fontSize: `calc(60px / ${columns.length})`, 
              color: '#fff',
              border: '1px solid #ccc',
              borderRadius: 5,
            }}
          >
            <h5>{column.name}</h5>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
  1. 启动应用程序:
npm start

使用您喜欢的 Web 浏览器访问http://localhost:3000并查看结果。

后记

本文介绍了在 JSX 的内联样式中使用calc()函数的基础知识。 您还制作了一个小而有意义的应用程序,它利用 calc() 动态设置元素的宽度和文本字体大小。通过创造性地应用这些知识,您可以构建令人惊叹的用户界面。