But, surely I could also just do this:
todos.map(Todo)
No, those are two different things. .map(x => <Todo title={x.title} dueDate={x.dueDate}/>)
calls React.createElement
to create the Todo
, but just .map(Todo)
simply calls Todo
directly.
You need to create the element, not just call the function. Those are fundamentally different things. <Todo ... />
doesn't call Todo
at all, it just calls React.createElement
, which will remember the Todo
function and call it as/when necessary. This doesn't call Todo
, for instance:
// Doesn't call `Todo`, just remembers it
const el = <Todo title={x.title} dueDate={x.dueDate}/>;
Later, if we use el
in another component or with ReactDOM.render
or similar, then Todo
will be called as necessary.
...instead of the verbose alternative.
If you're looking for something more concise, as jonrsharpe pointed out, you can do .map(x => <Todo {...x}/>)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…