Sorry this is more about lack of enough JS knowledge I think but my question is in my component if I have <td>{() => this.renderCell(item, col)}</td>
method being used like that it won't work but being called normally like I have in the component below then it works: What's the difference?
class TableBody extends Component {
renderCell = (item, column) => {
if (column.content) return column.content(item);
return _.get(item, column.path);
};
render() {
const { data, columns } = this.props;
return (
<tbody>
{data.map((item) => (
<tr>
{columns.map((col) => (
<td>{this.renderCell(item, col)}</td>
))}
</tr>
))}
</tbody>
);
}
}
Your anonymous function was defined but not called, which means it never runs this.renderCell(). To call it, you need to write it as ( () => /* function code */ )()
In your case: <td>{(() => this.renderCell(item, col))()}</td>
This is pretty unnecessary though, you should just do this: <td>{this.renderCell(item, col)}</td>
(as you did in your second snippet)
sorry that I can't just comment on this. But what happens is that when you call a function from inside an arrow function in React, like this:
<td>{() => myFunction()}</td>
It runs when you perform a specific action on that element, for example, when you click on a button:
<button onClick={() => myFunction} />
When you don't call it from inside an arrow function, like you are doing in your code snippet, that function gets called automatically, so, it renders your code:
// Runs automatically
<td>{myFunction()}</td>
// Only on specific trigger:
<td>{() => myFunction()}</td>
This is because what is expected inside the <td></td>
is a function, not a function call. So, you could either say handleSubmit
or () => handleSubmit()
, because they are both referring to a function, not a function call. handleSubmit()
however, is a function call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.