- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图让 App(组件)调用 Main(函数),而 Main(函数)又调用 Leads(组件),并且我希望 props 跟随。 Main 是返回我的应用程序的所有路由的函数。我正在使用 React Router v4。
我在下面尽可能地简化了代码,希望不要太多:
应用程序调用 Main 并传递 Prop :线索和库。
App.js
class App extends Component {
render() {
return (
<div>
<nav>
<Link to="/library">Library</Link>
<Link to="/leads">Leads</Link>
</nav>
<Main
leads={this.state.leads}
library={this.state.library}
/>
</div>
);
}
}
export default App;
这里有 Prop ,没问题。然而,我的理解是 props 是函数 Main 的局部变量,因此有一些指向它的东西是问题所在,因为一旦函数运行, props 就会被销毁。
Main.js (简化)
const Main = (props) => (
<main>
<Switch>
<Route exact path="/leads" render={(props) => (
<Lead
{...props}
leads={props.leads}
/> )}
/>
</Switch>
</main>
)
export default Main;
这里,Leads.js 中的 this.props.leads 指向 null,并且 {Object.keys(this.props.leads)} 失败。 (为了简单起见,我删除了 renderLeads() 的代码)
Leads.js (简化)
class Lead extends React.Component {
render() {
return (
<div>
<h2>Leads</h2>
<table>
<tbody>
{Object.keys(
this.props.leads).map(
this.renderLeads)}
</tbody>
</table>
</div>
);
}
}
export default Lead;
我通过使 Main 成为 React.Component 的扩展类来“解决”了这个问题。我仍然觉得 Main 应该是一个函数,它只操作数据而不保存自己的数据......
提前致谢。
最佳答案
当您在内部作用域中声明一个变量,其名称与位于上层作用域中的另一个变量(在本例中为变量“props”)同名时,您的错误就被称为“变量阴影”。
在 Main.js 中,您正在渲染 <Lead />
将功能组件传递给路由,传递 props
路由器给你的,而不是你渲染时传递的 <Main />
在 App.js 中。
我知道这有点令人困惑,但这解释了为什么当您将 Main 更改为 Class 组件时它会起作用,您可能正在使用 this.props
进行调用, 正确的?所以在这种情况下,你调用的是正确的。
您可以决定是否 <Main />
应该是功能组件或类,但通常没有状态的组件应该是功能组件。您可以简单地更改外部范围(主范围)或内部范围(路由)中的 Prop 名称。示例:
<Route exact path="/leads" render={(routerProps) => (
<Lead
{...routerProps}
leads={props.leads}
/> )}
/>
现在,我们正在引导中传递正确的 Prop 。
关于javascript - React.js : Passing Props from a Function to a Component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46157598/
我是一名优秀的程序员,十分优秀!