我正在构建一个简单的todo应用来练习reactjs
我有3个组件,如下所示:
这是TodoAppComponent.js,它是其他两个组件的包装:
import AddTodoComponent from '../AddTodoComponent/AddTodoComponent';
class TodoAppComponent extends Component {
render() {
return (
<div id="page-content-wrapper">
<div className="container">
<div className="row">
<div className="col-lg-6 col-lg-offset-3">
<h1 className="m-b-md">What needs to be done?</h1>
<AddTodoComponent></AddTodoComponent>
</div>
</div>
</div>
</div>
);
}
}
export default TodoAppComponent;
我可以添加待办事项的AddTodoComponent.jsx:
import TodoItemComponent from '../TodoItemComponent/TodoItemComponent';
class AddTodoComponent extends Component {
constructor(props) {
super(props);
this.state = {
todo: '',
todoArray: []
};
}
addTodo(e){
this.setState({ todo: e.target.value });
this.state.todoArray.push(<TodoItemComponent todo={this.state.todo}></TodoItemComponent>);
}
handleChange(e) {
this.setState({ todo: e.target.value });
}
render() {
return (
<div>
<div className="input-group m-b-md">
<input type="text" className="form-control add-todo" placeholder="Todo..." value={this.state.todo} onChange={this.handleChange.bind(this)} />
<span className="input-group-btn">
<button className="btn btn-react" type="button" onClick={this.addTodo.bind(this)}>Add</button>
</span>
</div>
<ul className="list-group">
{this.state.todoArray}
</ul>
</div>
);
}
}
export default AddTodoComponent;
如您所见,我将TodoItemComponent
推送到状态数组。
这是TodoItemComponent.jsx:
class TodoItemComponent extends Component {
deleteTodo(){
// this.setState({
// data: update(this.state.data, {$splice: [[index, 1]]})
// })
}
render() {
console.log(this.props.todo, this.props.title);
return (
<div>
<li className="list-group-item todo-item">
<button className="btn btn-xs btn-react btn-circle m-r-md">
<span className="fa fa-check"></span>
</button>
{this.props.todo}
<span className="pull-right">
<button className="btn btn-xs btn-react btn-circle m-r-xs">
<span className="fa fa-pencil-square-o"></span>
</button>
<button className="btn btn-xs btn-react btn-circle" onClick={this.deleteTodo()}>
<span className="fa fa-trash-o"></span>
</button>
</span>
</li>
</div>
);
}
}
export default TodoItemComponent;
如你所见,我有一个按钮,可以删除待办事项。但是如何访问此文件中的状态以将其从状态数组中删除?
答案 0 :(得分:0)
你可以试试这个
deleteTodo(){
this.props.onDelete(this.props.todo);
}
并在 AdddTodoComponent
中 addTodo(e){
this.setState({ todo: e.target.value });
this.state.todoArray.push(<TodoItemComponent onDelete={this.delete} todo={this.state.todo}></TodoItemComponent>);
}
delete:function(index)
{
this.setState({
// data: update(this.state.data, {$splice: [[index, 1]]})
// })
}