I am learning react, what is the best practice for the following scenario? Given this data -
const person = {
name: "",
tasks: [
{name: "", done: false }
]
}
I want a form to edit both the name and the tasks at the same time - add, delete and edit the fields of the tasks.
What I was thinking:
<PersonForm>
<PersonName />
<TaskList />
</PersonForm>
The name can be easily edited by the example given by react documentation:
class PersonForm extends React.Component {
constructor(props) {
handleChange = event => {
this.setState({value: event.target.value});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<PersonName name={this.state.name} onChange={this.handleChange} />
<TaskList tasks={this.state.tasks}/>
<input type="submit" value="Submit" />
</form>
);
}
}
class PersonName extends
render() {
return (
<label>
Name:
<input type="text" value={this.props.value} onChange={this.props.onChange} />
</label>
)
}
}
I know the recommend lifting state up. So I can also easily put the addTask, removeTask methods in PersonForm.
class PersonForm extends React.Component {
. . .
addTask = event => {
this.setState(prev => ({ tasks: [...prev, {name: "", done: false}]}));
}
removeTask = key => {
this.setState(prev => prev.filter(t => t.key !== key);
}
. . .
But,
- How do I edit a list item?
- It seems to me the best way to encapsulate functionality would be for the addTask, deleteTask, updateTask functionality to be in the TaskList component. Am I wrong? It seems like PersonForm would get huge (in a real world example). Would this mean TaskList would need state? Basically, what is the best practice for this sub-list scenario?
Aucun commentaire:
Enregistrer un commentaire