React 中使用 css
方式一,内联样式
render() {
return (
<>
<div style={{ width: '100px', height: '100px', backgroundColor: 'pink'}}>react ts</div>
</>
)
}
方式二,外部样式
.square{
width:100px;
height:100px;
background-color:pink;
}
.tsx 文件
import React, { Component } from 'react';
import './home.css';
...
render() {
return (
<>
<div className="square">react ts</div>
</>
)
}
需求:点击按钮更改样式
import React, { Component } from 'react';
import './home.css';
interface IState {
width: number
}
class App extends Component<any, IState> {
constructor(props: any) {
super(props)
this.state = {
width: 200
}
}
change = () => {
this.setState((state) => ({
width: state.width - 100
}))
}
render() {
return (
<>
<div style={{ width: `${this.state.width}px`, height: '100px', backgroundColor: 'pink' }}>react ts</div>
<br />
<button onClick={this.change}>改变宽度</button>
</>
)
}
}
export default App;
需求:当 div 的宽度小于 180px 就由正方形变圆形
import React, { Component } from 'react';
import './home.css';
interface IState {
width: number
}
class App extends Component<any, IState> {
constructor(props: any) {
super(props)
this.state = {
width: 200
}
}
change = () => {
this.setState((state) => ({
width: state.width - 10
}))
}
render() {
return (
<>
<div className={this.state.width > 180 ? 'square' : 'circle'}></div>
<br />
<button onClick={this.change}>减少宽度</button>
</>
)
}
}
export default App;
.square{
width:100px;
height:100px;
background-color:pink;
}
.circle{
width: 100px;
height: 100px;
background-color:pink;
border-radius: 50%;
}
封装列表删除按钮组件
子组件:
import { Component } from 'react'
import { Button } from 'antd'
interface IProps {
id: number
callback: (id: number) => void
}
export default class DeleteUser extends Component<IProps, any> {
DeleteUser = () => {
this.props.callback(this.props.id)
}
render() {
return (
<>
<Button type="primary" danger onClick={this.DeleteUser}>删除</Button>
</>
)
}
}
父组件:
import { Component } from 'react';
import DeleteUser from './DeleteUser'
import './home.css';
import 'antd/dist/antd.css'
import { Button, Space, Table } from 'antd';
interface IUser {
id: number,
name: string
}
interface IState {
userList: IUser[]
}
class App extends Component<any, IState> {
constructor(props: any) {
super(props)
let tableList: IUser[] = []
for (let i = 0; i < 20; i++) {
tableList.push({
id: i,
name: 'user' + i
})
}
this.state = {
userList: tableList,
}
}
DeleteUser = (id: number) => {
console.log(id)
this.setState(() => ({
userList: this.state.userList.filter(item => item.id !== id)
}))
}
render() {
return (
<>
<Table
dataSource={this.state.userList}
rowKey='id'
>
<Table.Column title={"ID"} dataIndex='id' />
<Table.Column title={"姓名"} dataIndex='name' />
<Table.Column title={"操作"} render={(user: IUser) => (
<Space>
<Button type="primary" >编辑</Button>
<DeleteUser id={user.id} callback={this.DeleteUser} />
</Space>
)} />
</Table>
</>
)
}
}
export default App;
|