【问题标题】:Passing props to child component issue [duplicate]将道具传递给子组件问题[重复]
【发布时间】:2019-05-25 04:26:02
【问题描述】:

我试图将一个道具传递给一个子组件,但当我控制台记录它时,它根本没有出现在道具中。甚至键 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 };

【问题讨论】:

    标签: javascript reactjs routes react-redux react-router


    【解决方案1】:

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

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

    让我知道它是否有效。

    说明: 当您使用&lt;Route path='/testing' things="yes" component={Child} /&gt; 时,您没有将道具传递给子组件,而是传递给路由组件,它忽略了它。

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

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

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

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

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

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

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

    【讨论】:

    • 它工作...你能进一步解释这段代码吗?
    • @HeelMega 我刚刚在答案中添加了解释。看看吧。
    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2020-12-19
    • 2020-10-08
    • 2021-03-27
    相关资源
    最近更新 更多