使用React.js写一个类似单选框与复选框的功能
单选框
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<style>
.item{
width: 20px;
height: 20px;
margin: 20px 0;
border: 1px solid #666;
}
.item>div{
height: 20px;
}
.checked{
background: red;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class CheckBox extends React.Component {
constructor(props) {
super(props);
this.state = {
tagIndexList: [],
value:[],
index:null,
arr: [
{
item: "item1"
},
{
item: "item2"
},
{
item: "item3"
},
{
item: "item4"
}
]
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(num,item){
this.setState({
index:num
})
console.log(item);
}
render() {
return (
<div>
{
this.state.arr.map((item, index) => {
return (
<div key={item.item} className="item">
<div className={this.state.index===index?"checked":""} onClick={()=>this.handleClick(index,item.item)}></div><span>{item.item}</span>
</div>
)
})
}
</div>
)
}
}
ReactDOM.render(
<CheckBox />,
document.getElementById('root')
)
</script>
</body>
</html>
复选框
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<style>
.item{
width: 20px;
height: 20px;
margin: 20px 0;
border: 1px solid #666;
}
.item>div{
height: 20px;
}
.checked{
background: red;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
更多内容请见原文,原文转载自:http://www.mark-to-win.com/tutorial/50842.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?