import * as React from 'react';

interface IData {

id: number,

title: string

}

interface IState {

checkedValues: Set;

data: IData[];

}

interface IProps {

value: IData,

checked: boolean,

onChange: (v: IData) => void

}

class ItemComp extends React.Component {

shouldComponentUpdate(nextProps: IProps) {

const props = this.props;

return props.value !== nextProps.value || props.checked !== nextProps.checked

}

render() {

const { value, checked } = this.props;

return (

type="checkbox"

checked={checked}

onChange={this.onChange} />

{value.title}

)

}

onChange = () => {

this.props.onChange(this.props.value);

}

}

// tslint:disable-next-line:max-classes-per-file

export default class App extends React.Component<{}, IState> {

constructor(props: {}) {

super(props)

const initValue: IState = {

checkedValues: new Set(),

data: []

}

for (let i = 0; i < 20000; i++) {

let temp = { id: Math.random(), title: i }

initValue.data.push(temp)

initValue.checkedValues.add(temp)

}

this.state = initValue;

}

render() {

const onChange = this.onChange;

const { checkedValues, data } = this.state;

return (

{data.map((value) =>

key={value.id}

value={value}

checked={checkedValues.has(value)}

onChange={onChange} />

)}

);

}

onChange = (active: IData) => {

const checkedValues = new Set(this.state.checkedValues);

if (checkedValues.has(active)) {

checkedValues.delete(active);

} else {

checkedValues.add(active);

}

this.setState({ checkedValues })

console.log(checkedValues)

}

}

 

 

比较慢的代码案例:

import React, { Component } from 'react';

import { Checkbox } from 'antd'

class App extends Component {

constructor(props) {

super(props)

this.state = {

checked: []

}

}

render() {

let list = this.list()

return (

{list}

);

}

}

Object.assign(App.prototype, {

componentDidMount() {

let arr = []

for (let i = 0; i < 20000; i++) {

arr.push(i)

}

this.setState({

checked: arr

})

},

list() {

let { checked } = this.state

let arr = []

for (let i = 0; i < 20000; i++) {

arr.push(= 0} onChange={this.handleChange.bind(this, i)}>{i})

}

return arr

},

handleChange(index, e) {

let { checked } = this.state

let tempIndex = checked.indexOf(index)

if (e.target.checked) {

if (tempIndex < 0) {

checked.push(index)

}

} else {

if (tempIndex >= 0) {

checked.splice(tempIndex, 1)

}

}

this.setState({

checked: checked

})

console.log(checked)

}

})

export default App

 

相关链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。