简体   繁体   English

如何返回一个 HTML<div> 从 React 中的 javascript 函数标记?

[英]How to return an HTML <div> tag from a javascript function in React?

I am working on a React application where I am trying to render text on the screen when a button is clicked.我正在开发一个 React 应用程序,当单击按钮时,我试图在屏幕上呈现文本。 I have defined a function onButtonClick which gets triggered whenever the button is clicked.我定义了一个 onButtonClick 函数,只要单击按钮就会触发它。 However, the HTML that I am returning from the function is not rendered on the screen.但是,我从该函数返回的 HTML 未呈现在屏幕上。 I am in the learning stages of React so please excuse me if the question seems silly.我正处于 React 的学习阶段,所以如果这个问题看起来很愚蠢,请原谅我。

class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}


OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(
      <div>
          <h3>Some text</h3>
      </div>
    );

}


render() {
return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
    </div>
    );
}

}

The value is being returned, but the framework/browser/etc.该值正在返回,但框架/浏览器/等。 has no reason to do anything with that value.没有理由对该值做任何事情。

Try thinking about this a different way, a "more React way".尝试以不同的方式思考这个问题,一种“更 React 的方式”。 You don't want to return the value to be rendered, you want to update state .您不想返回要呈现的值,而是想更新 state Something like this:像这样的东西:

constructor() {
  super();

  this.state = {
    blockno:0,
    showDiv: false // <-- note the new property in state
  }
}


OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}

Now you're not returning anything, but rather updating the state of the component.现在你没有返回任何东西,而是更新组件的状态。 Then in your render method you conditionally render the UI based on the current state:然后在您的render方法中,您根据当前状态有条件地渲染 UI:

render() {
  return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
        {
            this.state.showDiv
              ?
                <div>
                  <h3>Some text</h3>
                </div>
             : ''
        }
    </div>
    );
}

The click handler doesn't modify the page, it just modifies the state of the component you're writing.单击处理程序不会修改页面,它只会修改您正在编写的组件的状态。 The render method is responsible for rendering the UI based on that state. render方法负责根据该状态渲染 UI。 Any time state changes, render will be called again to re-render the output.任何时候状态改变, render都会被再次调用以重新渲染输出。

(Note: It's not 100% clear if this is exactly the functionality you're looking for in the UI, since it's not really clear what you're trying to build. But the point here is to illustrate how to update state and render output in React. Your logic can be tweaked as needed from there.) (注意:这是否正是您在 UI 中寻找的功能并不是 100% 清楚的,因为它并不清楚您正在尝试构建什么。但这里的重点是说明如何更新状态和呈现输出在 React 中。您可以根据需要从那里调整逻辑。)

You have to make a render based on your state.您必须根据您的状态进行渲染。 Please check the tutorial at the react docs to learn more about how React works.请查看 react 文档中的教程以了解有关 React 工作原理的更多信息。 It's really good真的很棒

Here is a version of your code that works.这是您的代码的一个有效版本。 Hope it helps希望能帮助到你

class App extends Component {
  constructor() {
    super();

    this.state = {
      blockno: 0
    };
  }

  OnButtonClick = () => {
    //updates the states
    this.setState({ blockno: this.state.blockno + 1 });
  };
  //remember: every time there is an update to the state the render functions re-runs
  render() {
    //variable holding the blocks in an array
    let blocks = []
    //if blockno is greater than 0, it checks everytime that there is a state change
    if (this.state.blockno > 0) {
      //for every block added
      for (let index = 0; index < this.state.blockno; index++) {
        //We`re going to add to the array of blocks a new div with the block number
        blocks.push(
          <div>
            <h3>My block number is {index}</h3>
          </div>
        );
      }
    }
    return (
      <div>
        <div>
          {/**button that updates the state on every click */}
          <button onClick={this.OnButtonClick}>
            Click me to add a new div!
          </button>
        </div>
        {/**This render the blocks variable that holds the divs */}
        {blocks}
      </div>
    );
  }
}

What I see is that you are trying to build a counter.我看到的是你正在尝试建立一个计数器。 The value that you're returning from the click handler function can't be rendered, instead you need to manage it in the render function as follow:您从单击处理程序函数返回的值无法渲染,您需要在渲染函数中管理它,如下所示:

    class App extends Component {
      constructor() {
        super();

        this.state = {
          blockno: 0
        }
      }


      OnButtonClick = () => {
        this.setState(prevState => ({ blockno: prevState.blockno + 1 }));
      }


      render() {
        return(
          <div>
            {this.state.blockno > 0 && <div>some text {this.state.blockno}</div>}
            <Button onButtonClick={this.OnButtonClick} />
          </div>
        );
      }
    }

Also note that the setState method is asynchronous, please read the documentation https://reactjs.org/docs/react-component.html#setstate还要注意 setState 方法是异步的,请阅读文档https://reactjs.org/docs/react-component.html#setstate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM