How do I change the innerHTML of an element using React?

馋奶兔 提交于 2021-02-11 12:11:53

问题


I want to change innerHTML of a div, when I click on the button. I don't know why, but instead of getting an error, or getting the expected result it deletes to content and replacing it with "[object Object]".

How can I get it work?

import React from 'react';
import Login from './components/login.js';
import SignIn from './components/signin';

import './App.css';

function App() {
  function LoginOnClick(){
    document.getElementById("wrapper").innerHTML = <SignIn />;
  }
  return (
    <div className="container" id="wrapper">
      <button onClick={LoginOnClick}>Login</button>
      <Login />
    </div>
  );
}

export default App;

回答1:


With react you don’t have to set the innerHtml to do this, instead the more typical way is to have internal state in your component and conditionally render your SignIn component based off that. To use state the component either needs to be class or use hooks, classes are more traditional so I changed the component to be a class.

To make a class a react component you need to extend the class with the React.Component, this is because react components have lots of internal behaviours that you need to include with your class for it to be considered a component.

So

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      signIn: false,
    };

    this.LoginOnClick = () => {
      this.setState({ signIn: true });
    };
  }

  render() {
    if (this.state.signIn) {
      return (
        <div className="container">
          <SignIn />
        </div>
      );
    }

    return (
      <div className=“container”>
        <button onClick={this.LoginOnClick}>Login</button>
        <Login />
      </div>
    );
  }
}



回答2:


You can make use of Hooks (Added n React 16.8).

import React, {useState} from 'react';
import Login from './components/login.js';
import SignIn from './components/signin';

import './App.css';

function App() {
  const [signIn, setSignIn] = useState(false); 
  return (
    <div className="container" id="wrapper">
      {signIn ? <SignIn /> : <> //This is React Fragments syntax
      <button onClick={() => setSignIn(true)}>Login</button>
      <Login />
      </>
      }
    </div>
  );
}

export default App;


来源:https://stackoverflow.com/questions/57012027/how-do-i-change-the-innerhtml-of-an-element-using-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!