首页 > 解决方案 > 如何在 React 中正确设置组件样式

问题描述

我有以下组件Login。它的作用并不重要,但对于样式,您可以在渲染内部看到,我添加了loginStyle,columnStyleinputStyle. 这工作正常,但我有另一个组件Register与该组件几乎相同Login,只是进行了一些更改,这并不重要。但是在我的Register组件中,我有同样的东西columnStyle,,inputStyle而不是loginStyle我有registerStyle

我申请的风格LoginRegister完全一样。我的问题是我是否创建某种具有我创建的所有这些样式的组件(并且只创建一次以没有重复的代码)并以某种方式使用它来设置任何需要在不同组件中进行样式设置的样式,或者我只是保留一个单独的js文件包含所有这些样式并将其导入到单独的组件文件中。我只想知道专业人士接受的方式。我知道我们可以使用css,但我看到很多项目不使用css它们的组件样式。

import React from 'react';
import Button from '../Buttons/Button';

class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };

    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChange(event) {
    this.setState({
      [event.target.name]: event.target.value,
    });
  }

  onSubmit(event) {
    event.preventDefault();
    alert('Login button clicked');
  }

  render() {
    const loginStyle = {
      display: 'flex',
      flexDirection: 'row',
      rowGap: '15px',
    };

    const columnStyle = {
      display: 'flex',
      flexDirection: 'column',
      width: '100vw',
      rowGap: '30px',
    };

    const inputStyle = {
      fontSize: '40px',
      outline: 'none',
      border: 'none',
      borderBottom: '1px solid black',
    };

    return (
      <form onSubmit={this.onSubmit} style={loginStyle}>
        <div style={columnStyle}>
          <input
            style={inputStyle}
            placeholder='Enter your email...'
            type='email'
            name='email'
            value={this.state.email}
            onChange={this.onChange}
          />
          <input
            style={inputStyle}
            placeholder='Enter your password...'
            type='password'
            name='password'
            value={this.state.password}
            onChange={this.onChange}
          />
          <Button type='submit' />
        </div>
      </form>
    );
  }
}

export default Login;

标签: reactjsstyles

解决方案


每个组件制作一个 .css 文件或 modules.css 文件是更好的方法,这种技术将帮助您保持您的样式与您的组件分开,并且您可以使其更容易响应。如果您的示例对于两个或三个组件或 div 具有相同的样式 css,您可以使该样式全局化并在您的每个 js 文件中使用它。大多数元素都有 className 属性,您可以通过命名来编写样式,例如

<div className="columnStyle">
    <input
        className="inputStyle"
        placeholder='Enter your email...'
        type='email'
        name='email'
        value={this.state.email}
        onChange={this.onChange}
      />
</div>

在您的 .css 文件中,您可以添加样式

.columnStyle {
  display: 'flex',
  flexDirection: 'column',
  width: '100vw',
  rowGap: '30px',
};

.inputStyle {
  fontSize: '40px',
  outline: 'none',
  border: 'none',
  borderBottom: '1px solid black',
};

推荐阅读