如何在react js中打印html标记中的常量?
我需要在html标记中使用const中的localstorage值。如何做到这一点 我的js代码是:如何在react js中打印html标记中的常量?,html,reactjs,local-storage,Html,Reactjs,Local Storage,我需要在html标记中使用const中的localstorage值。如何做到这一点 我的js代码是: componentDidMount() { const userName = localStorage.getItem('userName'); console.log(userName); } 我需要使用的Html代码是: <Dropdown.Toggle className="nav-link count-indicator bg-transparent">
componentDidMount() {
const userName = localStorage.getItem('userName');
console.log(userName);
}
我需要使用的Html代码是:
<Dropdown.Toggle className="nav-link count-indicator bg-transparent">
<span className="profile-text"></span>
userName here
</Dropdown.Toggle>
这里的用户名
您可以通过在JSX中使用{}
包装值来呈现任何动态值
<Dropdown.Toggle className="nav-link count-indicator bg-transparent">
<span className="profile-text"></span>{localStorage.getItem('userName');}
</Dropdown.Toggle>
请在链接中找到工作代码沙盒首先,您需要在您的状态中定义
用户名
,以便您可以在componentDidmount
中为其分配值。那么你可以这样使用它-
class App extends Component {
constructor() {
super();
this.state = {
userName: null
};
}
componentDidMount() {
this.setState({userName: localStorage.getItem('userName')})
console.log(userName);
}
render() {
return (
<Dropdown.Toggle className="nav-link count-indicator bg-transparent">
<span className="profile-text"></span>
{this.state.userName}
</Dropdown.Toggle>
);
}
}
类应用程序扩展组件{
构造函数(){
超级();
此.state={
用户名:null
};
}
componentDidMount(){
this.setState({userName:localStorage.getItem('userName')})
console.log(用户名);
}
render(){
返回(
{this.state.userName}
);
}
}
不,它不是渲染,我认为需要这样做。用户名是那样的,但我不知道确切的方法。
class App extends Component {
constructor() {
super();
this.state = {
userName: null
};
}
componentDidMount() {
this.setState({userName: localStorage.getItem('userName')})
console.log(userName);
}
render() {
return (
<Dropdown.Toggle className="nav-link count-indicator bg-transparent">
<span className="profile-text"></span>
{this.state.userName}
</Dropdown.Toggle>
);
}
}