我一直在改进我正在学习使用基于类的组件的代码。我在没有参数的函数上取得了部分成功。但其余的没有转换。
有效的方法:
这个
const About = () => (
<div>
<h2>About</h2>
</div>
)
到
class About extends React.Component {
render() {
return (
<div>
<h2>About</h2>
<p>The content is here.</p>
</div>
);
}
}
尚未完成:
下面的组件是卡住的地方。我真的无法理解如何将此参数传递给基于类的方法。 params 是否可以在类的构造函数中作为 prop 或其他东西使用?
const Topic = ({match}) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
下面还有一个。
const Topics = ({match}) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
最佳答案
将函数组件转换为类组件:
- 将函数组件主体中的所有内容移动到类组件的
render
方法中。如果主体是 JSX 本身,只需从render
方法返回
即可。 - 通过解构
this.props
将您需要的 Prop 分配给常量。
注意:对于没有状态或需要生命周期方法的仅查看组件,您应该保留无状态组件。
主题之前:
const Topic = ({match}) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
转换后的主题:
class Topic extends React.Component {
render() {
const { match } = this.props;
return (
<div>
<h3>{match.params.topicId}</h3>
</div>
);
}
}
关于javascript - 将 'Const' ReactJs 组件转换为基于参数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47812148/