[英]How to convert const reactjs component to class based
I am trying to figure out how to convert this code 我试图弄清楚如何转换此代码
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
Into a class based component like this 变成这样的基于类的组件
class Home extends React.Component {
render() {
....
}
}
Normal const components I know how to convert, but I am not able to understand how to include match
parameter in class based component. 普通的const组件我知道如何转换,但是我无法理解如何在基于类的组件中包含
match
参数。
In your functional component definition 在您的功能组件定义中
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
The argument is the props passed down to the Child component, however when you use {match}
you are detructuring only the prop match from all the props passed down. 参数是传递给Child组件的道具,但是,当您使用
{match}
您将从传递的所有道具中仅破坏道具匹配。
See this answer: What is the children prop in React component and what PropTypes do 看到这个答案: 什么是React组件中的子道具以及什么PropTypes做
So when converting your functional component to the class component you can destructure
the prop match
in the render
function like 所以,你的功能组件转换为类组件的时候可以
destructure
道具match
的render
功能类似
class Child extends React.Component {
render() {
var {match} = this.props;
return (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
}
}
function: 功能:
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
Class: 类:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.