【问题标题】:How to convert const reactjs component to class based如何将 const reactjs 组件转换为基于类
【发布时间】:2017-07-25 08:02:13
【问题描述】:

我正在研究如何转换这段代码

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

像这样进入基于类的组件

class Home extends React.Component {

  render() {
      ....
  }
}

普通的 const 组件我知道如何转换,但我不明白如何在基于类的组件中包含 match 参数。

【问题讨论】:

  • { match } 在转换时通常会映射到基于类的组件中的 this.props.matchthis.state.match。取决于匹配是否可能在组件的生命周期中发生变化。如果 match 可能发生变化,则将其设为 state 变量,否则将其设为 prop 变量。此外,需要检查您如何在父组件中创建子组件,以确保您正确传递道具或状态。

标签: javascript reactjs


【解决方案1】:

在你的功能组件定义中

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

参数是传递给子组件的道具,但是当您使用{match} 时,您只会从所有传递的道具中分解道具匹配。

看到这个答案:What is the children prop in React component and what PropTypes do

所以当你将你的函数组件转换为类组件时,你可以在render 函数中destructure match 之类的道具

class Child extends React.Component {

  render() {
      var {match} = this.props;
      return (
         <div>
             <h3>ID: {match.params.id}</h3>
           </div>
      )
  }
}

【讨论】:

    【解决方案2】:

    功能:

    const Child = ({ match }) => (
      <div>
        <h3>ID: {match.params.id}</h3>
      </div>
    )
    

    类:

    import React, { Component } from 'react';
    
    class Child extends Component {
      render(){
        const {match} = this.props;
        return (
          <div>
             <h3>ID: {match.params.id}</h3>
           </div>
        );
      }
    }
    export default Child;
    

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 2021-11-24
      • 2021-11-12
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      相关资源
      最近更新 更多