反应-如何检查待办事项列表中的项目?

时间:2019-12-01 21:35:55

标签: reactjs

我有一个待办事项清单,我想在已检查的项目上应用CSS(删除线),不仅删除它们(还存储检查的值),但无法弄清楚如何正确地做到这一点。任何想法都很棒!顺便说一句,我知道它不是最佳实践代码审查的地方,但是关于我的代码结构的任何观点都非常受欢迎,因为我正在努力改进!谢谢!

class TodoWrapper extends React.Component {
    state = {
        todos: [],
        currentItem: {text: "", id: "", checked: false}
    };

    onChange = (input) => {
        this.setState({
            currentItem: {
                text: input,
                key: Date.now() / Math.random()
            }
        })
    };

    addItem = (e) => {
        e.preventDefault()
        const newItem = this.state.currentItem
        if (newItem.text !== '') {

            const todos = [...this.state.todos, newItem]

            this.setState({
                todos: todos,
                currentItem: { text: '', key: '', checked: false },
            })
        }
    };
// here I could delete them but I dont know how to not delete and just mark checked (with strike through css)
    deleteItem = key => {
        const filteredItems = this.state.items.filter(item => {
            return item.key !== key
        })
        this.setState({
            items: filteredItems
        })
    }

    render () {
        return (
            <React.Fragment>
                <AddItem
                    addItem={this.addItem}
                    onChange={this.onChange}
                    currentItem={this.currentItem}
                />
                <List
                    todos={this.state.todos}
                    handleCheck={this.handleCheck}
                    deleteItem={this.deleteItem}
                />
            </React.Fragment>
        )
    }
}



const AddItem = ({addItem, currentItem, onChange}) => {

    const onInputChange = (event) => {
        onChange(event.target.value)
    };

    return (
        <form onSubmit={addItem}>
            <input value={currentItem} onChange={onInputChange}/>
            <button type="submit">Add</button>
        </form>
    )
};

const renderList = todos.map(item=> {
        return (               
                <li key={item.id}>{item.text}
                 <input
                     type="checkbox"
                     checked={item.isChecked}
                 />
                </li>React - h
        )
    });

    return (
        <ul>
            {renderList}
        </ul>
    )
};

1 个答案:

答案 0 :(得分:0)

您将根据是否item.isChecked创建一个类或样式。

例如


<li key={item.id}>
  <span style={{textDecoration: item.isChecked ? "line-through" : "none" }} > 
    {item.text}
  </span>
  <input
  type="checkbox"
  checked={item.isChecked}
  />
</li>