[英]Why are my props null when I use a method call inside render with JSX?
I have a FileList component that has child File components. 我有一个具有子File组件的FileList组件。 This was working fine:
这工作正常:
<tbody id="documents">
{files.map((file, i) => {
return (
<File
key={i}
id={file.id}
name={file.name}
path={file.path_lower}
tags={file.tags || []}
/>
);
})}
</tbody>
Then, I re-worked it a little when I was playing around and for some reason this isn't working (I'm getting a js error that indicates that the props are not being set on File). 然后,当我在玩耍时,我做了一些修改,由于某种原因,它不起作用(我收到了一个js错误,指示未在文件上设置道具)。 Essentially the code inside tbody got extracted into a helper method.
本质上,tbody中的代码被提取到一个辅助方法中。 My hunch is it has something to do with 'this', but in both cases, I'm operating on the same 'files' variable so that's not making sense to me.
我的直觉是它与“ this”有关,但是在两种情况下,我都在同一个“ files”变量上操作,所以对我来说这没有意义。
I'm curious why - anyone know? 我很好奇为什么-有人知道吗?
Here's the updated code: 这是更新的代码:
render() {
const files = this.state.files;
const elementsHtml = files.map((file, index) => {
return (
<File>
key={index}
id={file.id}
name={file.name}
path={file.path_lower}
</File>
);
});
return (
<table>
<thead>
<th key="name">
Title
</th>
<th alignleft="false" key="tag">
Categories
</th>
</thead>
<tbody id="documents">
{ elementsHtml }
</tbody>
</table>
)}}
In your last example, you are rendering File
component wrong. 在最后一个示例中,您使
File
组件错误。 You are not passing props to it, you are rendering it with some children. 您没有向其传递道具,而是将其与一些孩子一起渲染。 See:
看到:
<File>
...
name={file.name}
...
</File>
not 不
<File ... name={file.name}... />
So, change it like that: 因此,像这样更改它:
<File
key={index}
id={file.id}
name={file.name}
path={file.path_lower}
/>
Also, avoid using indexes as keys. 另外,请避免将索引用作键。 You have a file id there, use it as key.
您在那里有一个文件ID,将其用作密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.