React组件示例
这是一个带有交互操作的React Todolist组件,如果您已经熟练掌握React,可以忽略这部分内容。
首先,在src
目录下,新建一个名为todolist
的文件,与index
文件同级,如下所示:
下面是Todolist
组件的代码:
import React from 'react'
import { Row, Col, Button, Input, Checkbox } from 'antd'
import { DeleteOutlined } from '@ant-design/icons'
// 标题组件
const Title = props => {
return <h3>todo list</h3>
}
// 列表展示组件,展示items、是否完成状态、删除事件
const List = props => {
const { items, onDelete, onChange } = props
const onCheckboxChange = e => {
const name = e.target.value
const checked = e.target.checked
onChange(name, checked)
}
const defaultValue = items && items.filter(item => item.status).map(item => item.name) || []
return (
<Checkbox.Group style={{ margin: '20px 0' }} defaultValue={defaultValue}>
<Row>
{items && items.length > 0 ? items.map(item => {
const unfinished = item.name
const finished = <span style={{ textDecoration: 'line-through' }}>{item.name}</span>
const label = item.status ? finished : unfinished
return (
<Col span={24}>
<Checkbox
onChange={onCheckboxChange}
value={item.name}>{label}</Checkbox>
<DeleteOutlined
onClick={() => onDelete(item.name)}
style={{ position: 'absolute', right: 0, top: 4, cursor: 'pointer' }}
/>
</Col>
)
}) : null}
</Row>
</Checkbox.Group>
)
}
// 添加item组件
const Add = props => {
const [state, setState] = React.useState('')
const onClick = () => {
props.onAdd(state)
setState('')
}
const onChange = e => {
const value = e.target.value
setState(value)
}
return (
<>
<Input placeholder={'请输入待办事项'} value={state} onChange={onChange} />
<Button block onClick={onClick}>添加</Button>
</>
)
}
// Todolist组件
const TodoList = props => {
// 初始化数据
const [items, setItems] = React.useState([
{ name: 'learn english', status: false },
{ name: 'weight less than 100', status: false },
{ name: 'have 100,000 deposit', status: true },
{ name: 'Learn guitar', status: false },
])
const onAdd = name => {
const newItems = [...items, { name, status: 0 }]
setItems(newItems)
}
const onDelete = name => {
const newItems = items.filter(item => item.name !== name)
setItems(newItems)
}
const onChange = (name, status) => {
const newItems = items.map(item => {
if (item.name === name) {
item.status = status
}
return item
})
setItems(newItems)
}
return (
<div style={{ width: 200, margin: '0 auto' }}>
<Title />
<List items={items} onDelete={onDelete} onChange={onChange} />
<Add onAdd={onAdd} />
</div>
)
}
export default TodoList
在index.js
中引入Todolist
并且注册到页面,代码如下.
import { app } from 'xadmin';
import TodoList from './todolist'
app.use({
name: 'iot.test',
routers: {
'/app/': {
path: 'myTest',
breadcrumbName: '我的测试组件页',
component: TodoList
},
}
})
预览页面
这个示例中,我们使用了Ant Design的组件库来构建交互式的Todolist组件。通过这个示例,你可以学习到如何使用React和Ant Design来构建实际的交互组件。