我试图了解何时使用React功能组件与类以及从文档中读取它们并没有真正详细说明.当你想要一个类的特定功能来制作一个组件时,你能给我一些下面的主要例子吗?
功能组件功能较弱但更简单,只需一个render()方法就像一个类组件.除非您需要仅在课程中提供的功能,否则我们建议您使用功能组件.
我的团队使用React MaterialUI库.为了提供一致的UI模式并使我们能够轻松定制MaterialUI的组件,我们将每个MaterialUI的组件包装在我们自己的组件中.例如:
const style = {} // our project custom style for ListItemText
const OurListItemText = ({primary, secondary, classes}: Props) => (
<MuiListItemText
primary={primary}
secondary={secondary}
className={classes.text}
/>
) // we only expose primary and secondary props of the original MuiListItemText.
// Team members are blocked from customising other MUIListItemText's props
export default withStyles(styles)(OurListItemText)
Run Code Online (Sandbox Code Playgroud)
MuiListItemText是原始的MaterialUI的组件,OurListItemText而是我们的包装器组件.在我们的项目中,只 OurListItemText允许使用.
作为上面的片段,OurListItemText除了将道具转发之外什么都不做MuiListItemText.但是,这会对性能产生很大影响:
ListItemText顶部的酒吧来自OurListItemText下方的酒吧MuiListItemText.如果我们MuiListItemText直接使用,它可以快〜50%(我们已经尝试过),当我们有100时,这是显而易见的ListItemText.删除withStylesHOC略有改善,但并不显着. …
我想获取子组件的引用。做这个的最好方式是什么?
class Child extends React.Component {
render() {
return <div>Child</div>;
}
}
class GetRef extends React.Component {
componentDidMount() {
console.log(this.props.children.ref)
}
render() {
return this.props.children
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:所以我可以这样使用它
<GetRef><Child/></GetRef>
Run Code Online (Sandbox Code Playgroud) 目前,我有一个类组件,其中包含充当JSX中组件的功能。
例:
class MyComponent extends React.Component {
MySubComponent = (props) => {
if (props.display) {
return <p>This text is displayed</p>
}
}
render() {
return (
<this.MySubComponent display={true} />
)
}
}
Run Code Online (Sandbox Code Playgroud)
这样调用组件有什么影响吗?还有一个术语吗?
reactjs ×4
components ×2
javascript ×2
class ×1
material-ui ×1
performance ×1
react-props ×1
this ×1