gpt4 book ai didi

javascript - 无法使用创建 react 应用程序在 react 中添加类

转载 作者:行者123 更新时间:2023-12-01 01:42:47 25 4
gpt4 key购买 nike

react 有点新。我使用了创建 react 应用程序 https://github.com/facebook/create-react-app开始一个新的 react 项目。

完整的代码在这里。 https://github.com/bryandellinger/reactswitch/tree/master/src

我试图更改所选元素的背景颜色并将文本变为粗体,但似乎从未添加该类,不确定我做错了什么。

Switch.js

import React, { PropTypes } from 'react';
import styles from './Switch.css';

const CREDITCARD = 'Creditcard';
const BTC = 'Bitcoin';


const Choice = function (props) {
const cssClasses = [];

if (props.active) {
// <-- check props, not state
cssClasses.push(styles.active);
}

return (
<div
onClick={props.onClick}
className={cssClasses}
>
{props.label} {/* <-- allow any label */}
</div>
);
};

class Switch extends React.Component {
state = {
payMethod: BTC,
};

select = (choice) => {
return (evt) => {
this.setState({
payMethod: choice,
});
};
};

render() {
return (
<div className='switch'>
<Choice
onClick={this.select(CREDITCARD)}
active={this.state.payMethod === CREDITCARD}
label='Pay with Creditcard'
/>

<Choice
onClick={this.select(BTC)}
active={this.state.payMethod === BTC}
label='Pay with Bitcoin'
/>

Paying with: {this.state.payMethod}
</div>
);
}
}

export default Switch;

和 Switch.css

.active {
background-color: #4619eb;
font-weight: bold;
}

看来 switch.css 中的事件类永远不会添加到 onclick 事件上。不确定我错过了什么。

最佳答案

由于 Webpack 在 CRA 中的配置方式,您需要像这样编写 css:

 :local(.active) {
background-color: #4619eb;
font-weight: bold;
}

关于javascript - 无法使用创建 react 应用程序在 react 中添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com