Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在react js中打印html标记中的常量?_Html_Reactjs_Local Storage - Fatal编程技术网

如何在react js中打印html标记中的常量?

如何在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">

我需要在html标记中使用const中的localstorage值。如何做到这一点

我的js代码是:

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>
    );
  }
}