【问题标题】:How to print the const in html tag in react js?如何在反应js中打印html标签中的const?
【发布时间】:2020-02-20 12:54:04
【问题描述】:

我在 const 中有一个 localstorage 值,需要在 html 标记中使用。如何操作?

我的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>

【问题讨论】:

    标签: html reactjs local-storage


    【解决方案1】:

    您可以通过在 JSX 中使用 {} 包装值来呈现任何动态值

    <Dropdown.Toggle className="nav-link count-indicator bg-transparent">
       <span className="profile-text"></span>{localStorage.getItem('userName');} 
    </Dropdown.Toggle>
    

    或者,如果该值是动态的,并且当值更改时组件应该重新呈现,您可以将其存储在 state

    喜欢

     export default class App extends React.Component {
      state = {
        username: ""
      };
    
      componentDidMount() {
        localStorage.setItem("username", "TEST USERNAME");
        this.setState({ username: localStorage.getItem("username") });
      }
    
      componentWillUnmount() {
        localStorage.removeItem("username");
      }
    
      render() {
        return (
          <>
            <h1>Username from state is {this.state.username}</h1>
            <h1>
              Username directly from localStorage {localStorage.getItem("username")}
            </h1>
          </>
        );
      }
    }
    

    请在this链接中找到工作代码沙箱

    【讨论】:

    • 不,它不渲染我认为需要做类似this.userName这样的事情,但我不知道确切的方法。
    【解决方案2】:

    首先你需要在你的状态中定义userName,这样你就可以在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>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多