子方法可以在 React 中具有更改处理程序吗?
Can a child method have change handler in React?
我想知道为什么具有更改值的子组件没有在此处呈现。
让子进程处理自己的更改或者让控制器在父进程中更好不是一个好主意吗?
class App extends React.Component {
constructor() {
super();
this.state = {
todos: todosData
};
}
render() {
const todoItems = this.state.todos.map(item => (
<TodoItem key={item.id} item={item} />
));
return <div className="todo-list">{todoItems}</div>;
}
}
这是子 TodoItem
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.state = {
isComp: {}
};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
let tempObj = this.state.isComp;
tempObj.completed = !this.state.isComp.completed;
this.setState = { isComp: tempObj };
console.log(this.state.isComp);
}
render() {
this.state.isComp = this.props.item;
console.log(this.state.isComp);
return (
<div className="todo-item">
<input type="checkbox" checked={this.state.isComp.completed} />
<p>{this.props.item.text}</p>
</div>
);
}
}
如您所见,状态随 handleChange()
发生变化,但这不会触发渲染。我也不太确定是否可以将另一个对象分配给状态的对象(let tempObj = thi.state.isComp
)。
我想要实现的功能是选中和取消选中一个框并相应地进行渲染。
这是什么?
this.setState = { isComp: tempObj };
我觉得应该是
this.setState({ isComp: tempObj });
我想知道为什么具有更改值的子组件没有在此处呈现。
让子进程处理自己的更改或者让控制器在父进程中更好不是一个好主意吗?
class App extends React.Component {
constructor() {
super();
this.state = {
todos: todosData
};
}
render() {
const todoItems = this.state.todos.map(item => (
<TodoItem key={item.id} item={item} />
));
return <div className="todo-list">{todoItems}</div>;
}
}
这是子 TodoItem
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.state = {
isComp: {}
};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
let tempObj = this.state.isComp;
tempObj.completed = !this.state.isComp.completed;
this.setState = { isComp: tempObj };
console.log(this.state.isComp);
}
render() {
this.state.isComp = this.props.item;
console.log(this.state.isComp);
return (
<div className="todo-item">
<input type="checkbox" checked={this.state.isComp.completed} />
<p>{this.props.item.text}</p>
</div>
);
}
}
如您所见,状态随 handleChange()
发生变化,但这不会触发渲染。我也不太确定是否可以将另一个对象分配给状态的对象(let tempObj = thi.state.isComp
)。
我想要实现的功能是选中和取消选中一个框并相应地进行渲染。
这是什么?
this.setState = { isComp: tempObj };
我觉得应该是
this.setState({ isComp: tempObj });