我试图将一个 prop 传递给 react 中的子组件,但当我控制台记录它时,它根本没有显示在 props 中。连 key things
别出现。
对此的任何帮助将不胜感激。
export default class Child extends Component {
constructor(props) {
super(props);
console.log(props)
}
render() {
console.log(this.props)
return (
<div>
Test
</div>
);
}
}
class Parent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Router>
<div>
<Route path='/testing' things="yes" component={Child} />
</div>
</Router>
</div>
);
}
}
}
const connectedParent = connect()(Parent);
export { connectedParent as Parent };
最佳答案
在您的父组件中将 Route 替换为以下内容,
<Route
path='/testing'
render={(props) => <Child {...props} things="yes" />}
/>
让我知道它是否有效。
说明:
当您使用<Route path='/testing' things="yes" component={Child} />
时,您没有将 props 传递给 Child 组件,而是传递给 Route 组件,并且它忽略了它。
将 props 传递给 Route 中子组件的另一种方法是:
<Route
path='/testing'
component={() => <Child things="yes" />}
/>
但是使用方法,你会丢失路线 Prop ,例如位置、历史记录和其他 Prop ,并且根据文档:
当您使用组件 props 时,路由器使用 React.createElement 从给定组件创建一个新的 React 元素。这意味着如果您为组件属性提供内联函数,则每次渲染都会创建一个新组件。这会导致卸载现有组件并安装新组件,而不仅仅是更新现有组件。
所以我们只剩下我建议的方法,即
<Route
path='/testing'
render={(props) => <Child {...props} things="yes" />}
/>
在这里,您将诸如事物之类的 Prop 传递给子组件本身,而不是路线,并且路线的渲染方法也提供了路线 Prop 。因此,请始终记住将其 props 作为 {...props} 传递,以便您可以访问子组件中的 Route props,并且在路由时不会遇到任何问题。
关于javascript - 将 props 传递给子组件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53939991/