嗨,我需要一些帮助,使如何使reactJS网站的所有新示例都显示类似的示例
const NavBar = (params) => {
return(
<div>
text
</div>
)
}
export default NavBar;
然而,material-UI似乎显示以下内容,这使我很难理解如何使选项卡与上述新代码格式一起使用。有人可以帮忙解释一下构造函数如何以新格式工作吗?一个有效的制表符示例将非常棒(但可能要求太多)
import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
};
export default class TabsExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'a',
};
}
handleChange = (value) => {
this.setState({
value: value,
});
};
render() {
return (
<Tabs
value={this.state.value}
onChange={this.handleChange}
>
<Tab label="Tab A" value="a">
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs are also controllable if you want to programmatically pass them their values.
This allows for more functionality in Tabs such as not
having any Tab selected or assigning them different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="b">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
This is another example of a controllable tab. Remember, if you
use controllable Tabs, you need to give all of your tabs values or else
you wont be able to select them.
</p>
</div>
</Tab>
</Tabs>
);
}
}
编辑
我找到了我需要做的 通过使用useState,我可以检查用户正在访问哪个页面,并确保这是用户第一次进入该站点,然后设置一个const,然后让我随后运行另一个const来设置需要激活的选项卡。 / p>
const firstTime = false;
React.useState(() => {
if(!firstTime && window.location.pathname === "/two"){
//console.log('mounted or updated')
firstTime = 1;
}
}
);
const [value, setValue] = React.useState(firstTime);
答案 0 :(得分:0)
来自MDN:
“构造函数方法是用于创建和初始化在类中创建的对象的特殊方法。”
material-ui示例是一个类组件,而新示例是一个功能组件。功能组件不使用构造函数。
直到最近,当引入Hooks API时,如果一个组件需要使用State,它必须是一个类组件,但是有了Hooks,状态现在可以在函数组件内部进行操纵。我建议你仔细阅读。这是一个很好的入门: https://overreacted.io/how-are-function-components-different-from-classes/
以下是使用功能组件和挂钩的重构版本:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Tabs, Tab } from "@material-ui/core";
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400
}
};
const TabsExampleControlled = props => {
const [value, setValue] = useState("a");
return (
<Tabs value={value} onChange={(event, value) => setValue(value)}>
<Tab label="Tab A" value="a">
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs are also controllable if you want to programmatically pass them
their values. This allows for more functionality in Tabs such as not
having any Tab selected or assigning them different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="b">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
This is another example of a controllable tab. Remember, if you use
controllable Tabs, you need to give all of your tabs values or else
you wont be able to select them.
</p>
</div>
</Tab>
</Tabs>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<TabsExampleControlled />, rootElement);
查看