我想弄清楚如何转换此代码
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
进入这样的基于类的组件
class Home extends React.Component {
render() {
....
}
}
普通 const 组件我知道如何转换,但我无法理解如何match在基于类的组件中包含参数。
我想弄清楚如何转换此代码
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
进入这样的基于类的组件
class Home extends React.Component {
render() {
....
}
}
普通 const 组件我知道如何转换,但我无法理解如何match在基于类的组件中包含参数。
在您的功能组件定义中
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
参数是传递给子组件的props,但是当您使用时,您{match}只会从所有传递的props中解构props匹配。
请参阅此答案:React 组件中的 children 属性是什么以及 PropTypes 是做什么的
所以,你的功能组件转换为类组件时,你可以destructure在propsmatch中的render类似功能
class Child extends React.Component {
render() {
var {match} = this.props;
return (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
}
}
功能:
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;