我正在尝试在React js中使用className
向按钮添加样式。但这没用。它显示如下的默认样式。有人可以帮忙吗?
这是我的代码。
home.js
import React from "react";
export class Home extends React.Component{
constructor(props){
super();
this.age=props.age;
}
onMakeOlder(){
this.age +=3;
console.log(this.age);
}
render(){
return (
<div>
<p>in a new component!</p>
<p>your name is {this.props.name} , your age is {this.age}</p>
<hr/>
<button onClick={this.onMakeOlder.bind(this)} className="btn btn-primary">Make me older!</button>
</div>
);
}
}
Home.propTypes={
name: React.PropTypes.string,
age: React.PropTypes.number
/*user: React.PropTypes.object*/
};
已编辑
这是主页。
index.js
import React from "react";
import { render } from "react-dom";
import {Header} from "./components/Header";
import {Home} from "./components/Home";
class App extends React.Component {
render() {
/* var user={
name:"Senarath",
hobbies: ["games","sports"]
};*/
return (
<div className="container">
<div className="row">
<div className="col-xs-10 col-xs-offset-1">
<Header/>
</div>
</div>
<div className="row">
<div className="col-xs-10 col-xs-offset-1">
<Home name={"Pasindu"} age={24} />
</div>
</div>
</div>
);
}
}
render(<App/>,window.document.getElementById("app"));
webpack.config.js
var webpack =require("webpack");
var path = require("path");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "/app/index.js",
output: {
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/app/"
},
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
},
],
}
};
module.exports = config;
这是我得到的错误。
答案 0 :(得分:1)
您可以通过类型轻松抓住按钮。 ClassName也不适合我。 “类型”解决方案对我而言效果很好:
HTML:
<button type="no-margin">Button</button>
CSS:
button,
[type="no-margin"] {
margin: 0;
}
答案 1 :(得分:0)
在公用文件夹中写入一个CSS文件。并将该CSS文件链接到您的index.html文件。
public / css / custom.css
.some-class {
'color' : red
}
public / index.html
<link href="css/custom.css" rel="stylesheet" type="text/css" />
然后在边className="some-class"
中使用css calss
OR
您可以直接这样做
style = {{'color' : 'red'}}
OR
render() {
const text-color = {
'color' : 'red'
}
return <div style={text-color}></div>
}
答案 2 :(得分:0)
您似乎使用了bootstrap
。如果您还使用webpack
和node_modules
(此文件夹应位于项目的根目录中),则查看bootstrap文件夹是否存在。如果是这样,则可以通过以下方式进行连接:
import React from "react";
import "bootstrap/dist/css/bootstrap.css";
如果该文件夹不存在,请通过命令npm install bootstrap
安装它,您应该会看到适当的样式。
还应该在rules
配置的webpack
部分中添加css-loader:
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
https://github.com/webpack-contrib/css-loader
编辑:
对于旧版本的webpack,请使用loaders
关键字:
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
},
],
}