首页 > 解决方案 > 将道具传递给子组件问题

问题描述

我正在尝试将道具传递给子组件进行反应,但是当我控制台记录它时它根本没有出现在道具中。连钥匙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 };

标签: javascriptreactjsroutesreact-reduxreact-router

解决方案


在您的父组件中,将 Route 替换为以下内容,

<Route
  path='/testing'
  render={(props) => <Child {...props} things="yes" />}
/>

让我知道它是否有效。

说明:当您使用 时<Route path='/testing' things="yes" component={Child} />,您没有将道具传递给 Child 组件,而是传递给 Route 组件并且它忽略了它。

在 Route 中将 props 传递给 Child 组件的另一种方法是:

<Route
  path='/testing'
  component={() => <Child things="yes" />}
/>

但是使用方法,您会丢失 Route 道具,例如位置,历史记录和其他道具,并且根据文档:

当您使用组件道具时,路由器使用 React.createElement 从给定组件创建一个新的 React 元素。这意味着如果您为组件属性提供内联函数,您将在每次渲染时创建一个新组件。这会导致现有组件卸载和新组件安装,而不是仅仅更新现有组件。

所以我们留下了我建议的方法,即

<Route
      path='/testing'
      render={(props) => <Child {...props} things="yes" />}
    />

在这里,您将诸如事物之类的道具传递给子组件本身,而不是路由,并且 Route 的渲染方法也提供了 Route 道具。所以请始终记住将它的 props 作为 {...props} 传递,这样您就可以在 Child 组件中访问 Route props,并且在路由时不会遇到任何问题。


推荐阅读