English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this chapter, we will explain the React component API. We will discuss three methods: setState(), forceUpdate, and react . finddomnode(). In the new ES6In the class, we must manually bind it. We will use this.method.bind(this) in the example.
Set state
setState()The method is used to update the component's state. This method does not replace the state, but only adds changes to the original state.
import React from 'react'; class App extends React.Component { constructor() { super(); this.state = { data: [] } this.setStateHandler = this.setStateHandler.bind(this); }; setStateHandler() { var item = "setState..." var myArray = this.state.data.slice(); myArray.push(item); this.setState({data: myArray}) }; render() { return ( <div> <button onClick = {this.setStateHandler}>SET STATE</button> <h4>State Array: {this.state.data}</h4> </div> ); } } export default App;
We start with an empty array. Each time the button is clicked, the state is updated. If clicked five times, the following output will be obtained.
Sometimes we may want to manually update the component. This can be done usingforceUpdate()to implement the method.
import React from 'react'; class App extends React.Component { constructor() { super(); this.forceUpdateHandler = this.forceUpdateHandler.bind(this); }; forceUpdateHandler() { this.forceUpdate(); }; render() { return ( <div> <button onClick = {this.forceUpdateHandler}>FORCE UPDATE</button> <h4>Random number: {Math.random()}</h4> </div> ); } } export default App;
We are setting a random number that will be updated every time the button is clicked.
For DOM operations, we can use methods. First, we need to import.ReactDOM.findDOMNode()react-dom
import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor() { super(); this.findDomNodeHandler = this.findDomNodeHandler.bind(this); }; findDomNodeHandler() { var myDiv = document.getElementById('myDiv'); ReactDOM.findDOMNode(myDiv).style.color = 'green'; } render() { return ( <div> <button onClick={this.findDomNodeHandler}>FIND DOME NODE</button> <div id="myDiv">NODE</div> </div> ); } } export default App;
myDivAfter clicking the button, the color of the element becomes green.
Note−Since 0.14Since the update, it is not recommended to use most of the old component API methods or to delete them to adapt to ES6.