我只是从React开始,我正在尝试实现问候语,其中用户会根据一天中的时间获得不同的问候语。我熟悉执行此操作的JavaScript函数,只是不确定如何直接将其插入我的代码中。这是我到目前为止在React中拥有的navbar组件。
import React, { Component } from 'react'
import { Dropdown, Menu, Item, Image, Grid} from 'semantic-ui-react'
const userName = {
username: 'Alyssa'
}
class NavBar extends Component {
state = {
activeItem: 'sites',
}
handleItemClick = (e, { name }) => this.setState({
activeItem: name
})
render() {
const {activeItem} = this.state;
return (
<div>
<Menu inverted vertical>
<Item>
<Image size="tiny" centered src="https://s3.amazonaws.com/whatif-assets-cdn/images/what_ifcolonizer.png"></Image>
</Item>
<Grid columns={2} divided>
<Grid.Row>
<Grid.Column>
<Item>
<Image size="tiny" circular src="https://randomuser.me/api/portraits/men/20.jpg"/>
</Item>
</Grid.Column>
<Grid.Column>
<Item>
<Item.Description>
Hello, {userName.username}
</Item.Description>
</Item>
</Grid.Column>
</Grid.Row>
</Grid>
<Dropdown item text='Sites'>
<Dropdown.Menu name='sites' active={activeItem === 'sites'} onClick={this.handleItemClick} >
<Dropdown.Item>Site Groups</Dropdown.Item>
<Dropdown.Item>Sites</Dropdown.Item>
<Dropdown.Item>Themes</Dropdown.Item>
<Dropdown.Item>Sequences</Dropdown.Item>
<Dropdown.Item>Landing Pages</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Menu.Item
name='Campaigns'
active={activeItem === 'Campaigns'}
onClick={this.handleItemClick}
/>
<Menu.Item
name='Users'
active={activeItem === 'Users'}
onClick={this.handleItemClick}
/>
<Menu.Item
name='Settings'
active={activeItem === 'Settings'}
onClick={this.handleItemClick}
/>
</Menu>
</div>
)
}
}
export default NavBar
我只是想在标签中添加问候语,以及用户名。
答案 0 :(得分:2)
这有点长,但是它应该涵盖您需要知道的所有内容。创建一个Greeting
组件。挂载此组件时,获取小时数,并且您可以根据小时数向用户显示不同的消息。
class Greeting extends React.Component {
state = {
hour: null,
username: 'Alyssa'
}
componentDidMount() {
this.getHour()
}
getHour = () => {
const date = new Date();
const hour = date.getHours()
this.setState({
hour
});
}
render(){
const {hour, username} = this.state;
return (
<div className='App'>
<h2>{hour < 12 ? `Good Morning ${username}` : `Good evening ${username}`}</h2>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Greeting />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>