reactjs - 如何在 React 中正确设置组件样式
问题描述
我有以下组件Login
。它的作用并不重要,但对于样式,您可以在渲染内部看到,我添加了loginStyle
,columnStyle
和inputStyle
. 这工作正常,但我有另一个组件Register
与该组件几乎相同Login
,只是进行了一些更改,这并不重要。但是在我的Register
组件中,我有同样的东西columnStyle
,,inputStyle
而不是loginStyle
我有registerStyle
。
我申请的风格Login
和Register
完全一样。我的问题是我是否创建某种具有我创建的所有这些样式的组件(并且只创建一次以没有重复的代码)并以某种方式使用它来设置任何需要在不同组件中进行样式设置的样式,或者我只是保留一个单独的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;
解决方案
每个组件制作一个 .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',
};
推荐阅读
- php - 如何使用 REST 接口退出 WordPress?
- c++ - 在客户端上使用 gRPC C++,如何保持库单线程?
- kotlin - Kotlin 中是否有任何方法可以将自定义函数添加到接口内的属性中?
- python - 查找两个列表之间的差异并在列表中打印它们的位置和值
- javascript - 用两个例子测试我对表达式和语句的理解
- python - 在多列上应用`pd.qcut`
- swift - 如何使用 Xcode12 键盘快捷键(_:)?
- javascript - 当 hasTVPreferredFocus 被忽略时,有没有办法强制关注 android TV 上的可选内容?
- javascript - HTML:引导验证表单(确认输入值等于字符串)
- python - 之字折线指标 Metastock 公式到 Python